Search code examples
xmlnext.jssitemapparse-server

How to generate dynamic sitemap in next js with sitemap package?


I'm using next js and back4app for my web application. I came across the sitemap library to write a sitemap, but I am not able to create a dynamic site map at all. I am not able to run any api calls or cloud code, I have a specific function which will return all the routes so that I can pipe them. Here is my sample code below:

import { SitemapStream, streamToPromise } from "sitemap";
const {Readable} = require("stream");
import cacheData from 'memory-cache';
import { initializeParse } from '@parse/react-ssr';



initializeParse( 
    'https://parseapi.back4app.com',
    '********************',
    '*********************'
  );

const sitemap = async (req,res) => {

    try{
        const links = [
            { url: "/blogggy", changefreq: "daily", priority: 0.3 },
        ];
        const userParams = {
            authKey: "***********************"
        }


         Parse.Cloud.run("getAllRoutes",userParams).then(response =>{
             response.map((handle) => {
                 links.push({
                   url: `/${handle}`,
                   changefreq: "daily",
                   priority: 0.9,
                 });
               })
         }).catch(e =>{
             res.send(JSON.stringify(e));
         })
        

        const pages = ["/explore"];
        pages.map((url) => {
          links.push({
            url,
            changefreq: "daily",
            priority: 0.9,
          });
        });
        
        const stream = new SitemapStream({hostname: `https://${req.headers.host}`}) ; 
        
        res.writeHead(200,{
            "Content-Type": "application/xml",
        });
        
        const xmlString = await streamToPromise(
            Readable.from(links).pipe(stream)
        ).then((data) => data.toString());
        
        res.end(xmlString);
    }
    catch(e){
        console.log(e);
        res.send(JSON.stringify(e));
    }
};


export default sitemap

I also tried getServerSideProps but it didn't work. How do I solve this issue?


Solution

  • Again, I'm not sure if that's the only problem with your code, but try to rewrite the cloud code function call to something like this:

    let response;
    try {
      response = await Parse.Cloud.run("getAllRoutes",userParams);
    }
    catch (e) {
      res.send(JSON.stringify(e));
      return;
    }
    response.map((handle) => {
      links.push({
        url: `/${handle}`,
        changefreq: "daily",
        priority: 0.9,
      });
    });