Creating Dynamic Sitemaps in Nuxt JS - Featured Image
Web development3 min read

Creating Dynamic Sitemaps in Nuxt JS

Have you ever been in the middle of your sprint tasks and suddenly been assigned something that made you go, "Wait, how do I even do that?" That's exactly what happened to me when I was asked to create dynamic sitemaps.

The challenge

I faced two main problems while working on this task. First was the dynamic data population where the sitemaps needed to show all active products, collections, and other live routes on the website. Static files weren't an option because who wants to deploy every time a product link gets updated? Not in this dev's world! The second issue was handling dynamic domains. The domain names in the sitemap had to match whatever domain the client was using to access the site. So if someone accessed from example.com, they should see routes with example.com, and if from abc.com, they should see abc.com routes.

The solution

After digging through Nuxt's docs and scratching my head for a while, I decided to try using serverMiddleware. I implemented this in Nuxt 2, but you should be able to use a similar approach in Nuxt 3 with minimal tweaking.

Step 1: Set up serverMiddleware in nuxt.config.js

First, I set up the serverMiddleware in nuxt.config.js to route sitemap requests properly. This configuration means that when someone visits example.com/sitemap.xml, they'll be routed to whatever logic is in the sitemap.js file.

export default {
  serverMiddleware: [
    {
      path: '/sitemap.xml',
      handler: "~/serverMiddleware/sitemap.js",
    }
  ]
}

Step 2: Create the sitemap generation handler

Now for the actual sitemap generation logic, I created a handler function that would fetch data from our backend and build the XML structure.

module.exports = async function handler(req, res, next) {
    try {
        const domain = "https://mydomain.com"
        const backendBaseURL = "https://backend-service";
        const response = await axios.get(`${backendBaseURL}/pages/sitemaps`);
        let data = response.data;
        let products = data.products;
        
        let timestamp = new Date();
        timestamp = timestamp.toISOString().replace("Z", "+05:00");

        let xmlData = `<?xml version="1.0" encoding="UTF-8"?>
            <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
             <sitemap>
             <urlset>`;
        products.forEach((product) => {
            xmlData += `
                <url>
                    <loc>${domain}/products/${product.identifier}</loc>
                    <lastmod>${timestamp}</lastmod>
                    <changefreq>daily</changefreq>
                    <image:image>
                        <image:loc>${product.image}</image:loc>
                        <image:title>${product.title}</image:title>
                        <image:caption/>
                    </image:image>
                </url>`)};
        xmlData += `</urlset></sitemap></sitemapindex>`;
        res.setHeader("Content-Type", "application/xml");
        res.end(xmlData);
     } catch (error) {
        res.statusCode = 500;
        res.end("Internal Server Error")
  }
}

Step 3: Implement dynamic domain handling

For the dynamic domain part, it's actually pretty straightforward. Instead of hardcoding the domain, I can grab it from the request headers:

const domain = req.headers.host

This simple line of code ensures that whatever domain the user is accessing the sitemap from, that same domain will be used in all the sitemap URLs.

Step 4: Enjoy automatic updates

The beauty of this approach is that it requires no additional deployments when your site content changes. The sitemap automatically updates whenever new products are added or existing ones are modified in your database.

Is this the most elegant solution ever? Probably not. But it gets the job done, and I haven't found a better way to handle this specific use case in either Nuxt 2 or Nuxt 3.

What I particularly like about this solution is how it solves both problems with minimal code. The serverMiddleware approach gives us the flexibility to generate completely dynamic content while also adapting to whatever domain is being used. For developers working with multi-domain Nuxt applications, this approach could save a ton of headaches when dealing with SEO requirements.

Conclusion

Implementing dynamic sitemaps in Nuxt JS doesn't have to be complicated. With just a few lines of code and leveraging the serverMiddleware feature, you can create sitemaps that automatically update with your content and adapt to different domains. This approach eliminates the need for constant redeployments and makes your SEO maintenance practically hands-free. The next time you're faced with this challenge, remember that sometimes the simplest solutions are the most effective. Happy coding!

Maybe in a future post, I'll dive deeper into how that XML string construction works, but this should get you up and running with dynamic sitemaps in your Nuxt application!

hassaankhan789@gmail.com

Frontend Web Developer

Posted by





Subscribe to our newsletter

Join 2,000+ subscribers

Stay in the loop with everything you need to know.

We care about your data in our privacy policy

Background shadow leftBackground shadow right

Have something to share?

Write on the platform and dummy copy content

Be Part of Something Big

Shifters, a developer-first community platform, is launching soon with all the features. Don't miss out on day one access. Join the waitlist: