DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Updated on • Originally published at

Nuxt 3 build configuration. Generate dynamic routes and sitemap in SSR

Cover image

Why do I favor Nuxt.js? Simple: its versatile building modes, especially SSR (Server-Side Rendering). Picture this: you're tasked with building a large-scale e-commerce platform boasting thousands of products or services, each requiring meticulous SEO optimization. Nuxt.js, particularly in SSR mode, proves invaluable in such scenarios. In a recent project akin to this, I delved deep into configuring 'nitro' to generate dynamic pages, sitemap routes, and SEO meta tags for every product. Recognizing the challenges, I decided to create a tutorial to ease the process for other developers. Let's dive into the intricacies of Nuxt.js build configuration together.

(Node js and npm last versions should be installed already)

Step 1: Let's begin.

Usually at the beginning, we talk about creating new applications and all necessary folders. But the topic is about generating final pages so I'm pretty sure you already have that project, if not check my previous post Step 1 section for example: Nuxt 3 SSR, Firebase 9. How to set firebase authentication and configure middleware to stay signed in with example

Your nuxt.config.ts file should looks like this:

default nuxt.config.ts

Step 2: Find out our needs.

Okay, what do we want from our Nuxt js (SSR) project when using "nuxt generate"? Easy, we want Nuxt to create a structured project with all folders and files. With our statically created pages we do not need to configure anything, Nuxt will generate the same pages and routes structure as in the "pages" folder of our project. What to do with dynamic pages? What to do with our sitemap? We need to create arrays and tell Nuxt which folders to create and which files and routes to use, how to do it will be in the next section.

(For sitemap I used nuxt-simple-sitemap module. You need only to install, add as a module, and add an array of routes that should be added to a sitemap file.)

Step 3: Configure nuxt.config.ts.

nuxt.config.ts is the main configuration file for a Nuxt.js project.
First of all, add a function that in the building process will fetch data that contains our routes. The "getProductsRoutes()" function as a result returns an array of URL strings. Each URL is a route for the generated page. Example:

const getProductsRoutes = async () => {
  try {
    const fetchData = await fetch(``);
    const data: Product[] = await fetchData.json();
    return Product) => `/blog/${post.slug}`);
  } catch (error: any) {
    console.error('Error:', error);
    return [];
Enter fullscreen mode Exit fullscreen mode

Great, next we need to customize the hooks of our "nitro" so that it will call our "getProductsRoutes()" function before generating the application.

Check full post...

Top comments (0)