Generating Sitemaps in next.js

ankita yadavankita yadav
2 min read

Sitemap is a file that provides information about your site routes, and site content to search engine crawlers and they will index your site content.
The most common formats for sitemap files are XML and also it can be in RSS and text format too.
It will be located in the root directory of your folder.

Let's try to create static as well as dynamic sitemap file :

we will use the next-sitemap package to create sitemap files.

Create next-sitemap.config.js in your root directory.

Static routes Sitemap

Add the below code in your next-sitemap.config.js file.

Go to package.json and add postbuild": "next-sitemap" to scripts.

Run this script using yarn run postbuild command and you will see a static sitemap.xml will be created in your public folder which will have all your static routes from the pages directory.

Dynamic routes sitemap

Create pages/server-sitemap.xml/index.tsx file and add below code there.

Add the below code in your next-sitemap.config.js file.

Go to package.json and add postbuild": "next-sitemap" to scripts.

Run this script using yarn run postbuild command and you will see a static sitemap.xml will be created in your public folder which will have all your static routes from the pages directory.

you can also visit your sitemap.xml file at /server-sitemap.xml route and see all routes added from your application there.

Do not forget to add yarn run postbuild in your deployment step.

2
Subscribe to my newsletter

Read articles from ankita yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ankita yadav
ankita yadav