Update Sitemap / File In NextJS Without Rebuilding Project (Dynamic Update)

Felix Lee
2 min readSep 18, 2022

Recently I receive a request to update the sitemap of a website periodically so that the crawler can get the latest content. A sitemap typically is located at the root of the domain (i.e. yourdomain.com/sitemap.xml). In another word, the sitemap.xml is stored in the public folder of the NextJS project.

Let’s us take a look at the NextJS documentation

Note: Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available. We recommend using a third party service like AWS S3 for persistent file storage.

Does this mean we have to rebuild and deploy our project every time just to update a file in NextJS? Nope! There’s one way we can do it — server side rendering.

TLDR, show me the code.

Basically, all you have to do is create a folder named sitemap.xml under the pages folder and serve your sitemap.xml “page”, like so pages/sitemap.xml/index.tsx .

Remember to remove the sitemap.xml in the public folder if you have any. NextJS will prompt an error if you have a static file and a page with the same name.

For this example, I host the sitemap.xml file on S3, feel free to use any storage service you prefer. So if we want to update sitemap.xml, we don’t have to build and deploy the project, we can just update the file in the S3 bucket!

You can check the full source code here

Thanks for reading! You can find me on LinkedIn or simply down me a message on Medium.

--

--

Felix Lee

Software engineer in Singapore. Write random tech stuff. Still figuring out this “life” thing in life.