Using next-sitemap to Generate Sitemaps
Sitemaps are vital for SEO; they help search engines better understand the structure and organization of your website, which can improve the ranking of your pages in search results. They’re essential to helping people find your website, and the next-sitemap npm package can help you easily set up sitemaps for your site.
Setting Up next-sitemap
- To install the package, go to the root of your Next.js application and run
npm i next-sitemap
. - Add a postbuild script to your
package.json
file. This will run thenext-sitemap
command afternpm run build
is called.
- Create a config file called
next-sitemap.config.js
under the root of your application.
- Edit your
.gitignore
file to prevent automatically generated sitemap files from being added to your git repository.
Generating Static Sitemaps
- Run
npm run build
in your terminal to trigger the postbuild script. The output of the command should list the URLs of the sitemaps and sitemap indices.
- Run
npm start
and visit the URL outputted by the previous command (usuallylocalhost:3000/sitemap-0.xml
) to see the generated sitemap.
Generating Sitemaps For Dynamic Routes
- Create a new
route.ts
file under yourapp
directory atapp/server-sitemap.xml/route.ts
. - Write a GET request handler to return an array of all your dynamic URLs using the
getServerSideSitemap
function.
- Edit your
next-sitemap.config.js
file to add your dynamic sitemap to your `robots.txt` file and exclude its URL from your appearing on your static sitemap.
- Run
next run build
again. Now both your static (http://localhost:3000/sitemap-0.xml
) and dynamic (http://localhost:3000/server-sitemap.xml) sitemaps should be there.
After following these steps, your website’s sitemaps should be automatically generated every time npm run build
is called. For more information and additional options, visit the next-sitemap documentation.
Found this article interesting? Chat with our account specialists to get started on your next digital journey.