DEV Community

Cover image for Struggling with Website Traffic? Learn How to Create Sitemaps in NextJS Today!
Sohail SJ | chakraframer.com
Sohail SJ | chakraframer.com

Posted on • Edited on

Struggling with Website Traffic? Learn How to Create Sitemaps in NextJS Today!

I used to think that once you make website connect a domain and you are done, after a few weeks your site will get massive traffic and I will be rich by AdSense.

after a few weeks your site will get massive traffic and you will be rich by AdSense

But that's not the case, you need to do a lot of things to get traffic to your website and one of the most important thing is SEO. And one of the most important part of SEO is sitemap.

So in this series, I will try to explain how to create sitemap for a website in your NextJS project. I will explain different approaches based on your requirements like static pages, dynamic pages, etc.

Table of Contents


What is sitemap?

A sitemap is a file where you provide information about the pages, videos, and other files on your site, and the relationships between them.

Basically, it is a way to tell search engines about pages on your site they might not otherwise discover like a map with routes to all your pages.


Why do you need a sitemap?

A sitemap is important as it helps search engines to understand your website structure while crawling it which results in better indexing of your website and better indexing means better ranking in search results and better ranking means more traffic to your website. Simple, right?

If sitemap is not provided, search engines will still crawl your website but it might take longer time to index your website and some pages might not be indexed at all.

You can also share this important XML file to google search console to monitor the indexing status of your website and to see if there are any errors. Check example below for ChakraFramer website.

Google Search Console For ChakraFramer


How to create sitemap using NextJS?

To keep things simple, I will be creating a sitemap for general structure of a website like home, about, contact, etc.

| app/pages
    | /
    | /about
    | /contact
    | /sitemap.xml
Enter fullscreen mode Exit fullscreen mode

For NextJS Page Router

  • Create a new folder sitemap.xml with a index.js file and add the following code if you using pages router in NextJS.
  • We will be using getServerSideProps to generate the sitemap.
  • Then we will cache the sitemap for a certain period of time to avoid generating it on every request.
  • View Code on Stackblitz
const CACHE_DURATION = 60 * 60 * 24 // 24 hours in seconds
const LAST_MODIFIED = new Date().toUTCString()
export const getServerSideProps = async ({ res }) => {
  const sitemap = `
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        <url>
          <loc>https://example.com/</loc>
          <lastmod>2021-09-01</lastmod>
          <changefreq>daily</changefreq>
          <priority>1.0</priority>
        </url>
        <url>
          <loc>https://example.com/about</loc>
          <lastmod>2021-09-01</lastmod>
          <changefreq>daily</changefreq>
          <priority>0.8</priority>
        </url>
        <url>
          <loc>https://example.com/contact</loc>
          <lastmod>2021-09-01</lastmod>
          <changefreq>daily</changefreq>
          <priority>0.8</priority>
        </url>
  </urlset>
    `
  res.setHeader('Content-Type', 'text/xml')
  res.setHeader('Cache-Control', `public, max-age=${CACHE_DURATION}`) // Cache for 24 hours
  res.setHeader('Last-Modified', LAST_MODIFIED)
  res.write(`<?xml version="1.0" encoding="UTF-8"?>`)
  res.end(sitemap) // Send the sitemap to the user
  return {
    props: {},
  }
}
const Sitemap = () => {
  return null // Return null as we are not rendering anything its just a server side code
}
export default Sitemap
Enter fullscreen mode Exit fullscreen mode

For NextJS App Router

  • Create a new folder in app folder sitemap.xml with a route.js file and add the following code if you using app router in NextJS.
  • We will be using GET request to send the sitemap.
  • Then we will cache the sitemap for a certain period of time to avoid generating it on every request.
  • View Code on Stackblitz
const CACHE_DURATION = 60 * 60 * 24 // 24 hours in seconds
const LAST_MODIFIED = new Date().toUTCString()
export async function GET(req: Request) {
  const sitemap = `
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                <url>
                    <loc>https://example.com/</loc>
                    <lastmod>2021-09-01</lastmod>
                    <changefreq>daily</changefreq>
                    <priority>1.0</priority>
                </url>
                <url>
                    <loc>https://example.com/about</loc>
                    <lastmod>2021-09-01</lastmod>
                    <changefreq>daily</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>https://example.com/contact</loc>
                    <lastmod>2021-09-01</lastmod>
                    <changefreq>daily</changefreq>
                    <priority>0.8</priority>
                </url>
    </urlset>
    `

  return new Response(sitemap, {
    status: 200,
    headers: {
      'Content-Type': 'text/xml',
      'Cache-Control': `public, max-age=${CACHE_DURATION}`, // Cache for 24 hours
      'Lats-Modified': LAST_MODIFIED,
    },
  })
}
Enter fullscreen mode Exit fullscreen mode

  • Now, if you visit https://example.com/sitemap.xml or http://localhost:3000/sitemap.xml it will look like image below.

Sitemap Example for NextJS

In the next part, I will explain how to create sitemap for using npm package next-sitemap. which eleminates the need to write the sitemap manually. automatically generates the sitemap for you. Stay tuned!

Get in touch

Platform Handle
Youtube @thesohailjafri
X/Twitter @thesohailjafri
LinkedIn @thesohailjafri
Instagram @thesohailjafri
Github @thesohailjafri

Top comments (0)