Lusera Tech
How to Supercharge Your Next.js SEO with Sitemaps

February 6, 2023

How to Supercharge Your Next.js SEO with Sitemaps

SEO is important for any website, but it’s even more critical for websites built with Next.js. If you’re not familiar with Next.js, it’s a React-based framework that helps developers build performant and SEO-friendly websites. This can come in handy when it comes to load speed and sitemaps.

One of the best ways to optimize your Next.js website for SEO is to generate a sitemap. A sitemap is an XML file that contains all the URLs of a website. Search engine crawlers use it to discover which pages and content exist on your website.

NextJS Setup

First, we’re going to assume that you already have a Next.js project setup. If not you can just use the default npx create-next-app@latest.

We will start of by creating some content to put in the nextjs sitemap. You can start off by creating random pages or if you want to go the extra mile you can create a blog in the pages/blog. For this measure you can just create static content on your blogs.

Let’s import our packages:

npm install next-sitemap

In Next.js, pages are based on the files contained in the “pages” directory. Each page is associated with a route based on its file name. Before a sitemap can be generated, the pages that reside on your website need to be known. The “next-sitemap” package takes care of this by dynamically generating the sitemap on each request using server-side rendering.

Setting up next-sitemap.config

To set up the next-sitemap.config file, you need to specify the options for generating your sitemap in a JSON format. This file is used by the next-sitemap package to configure how your sitemap will be generated.

The basic options you can specify in this file include the base URL of your site, the pages that should be included in the sitemap, and any additional properties you want to include in the sitemap such as the frequency of change or the priority of each page. You can find more information on the available options and how to use them in the official documentation for the next-sitemap package.

For starters here is a basic config file:

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.SITE_URL || 'http://www.example.com',
  generateRobotsTxt: true, // (optional)
  // ...other options
  exclude: ['/server-sitemap.xml'],
  robotsTxtOptions: {
    additionalSitemaps: ['https://www.example.com/server-sitemap.xml'],
  },
};

However, this will omst likely just get you your current pages in your nextjs app. For example, let’s say we had a blog or a list of categories, we wouldn’t want to add them one by one, instead we can use the api folder and request our data.

Here is an example below.

import { GET_POSTS } from '@/graphql/queries/query.tsx';
import { initializeApollo } from '@/utils/ApolloClient.tsx';

export default async function handler(req, res) {
  const client = initializeApollo();

  const { data } = await client.query({
    query: GET_POSTS,
  });
  const posts = data.posts.edges;
  const urls = posts.map((post) => ({
    loc: `https://example.com/${post.node.categories.nodes[0].slug}/${post.node.slug}`,
    lastmod: new Date(post.node.date).toISOString().split('T')[0],
  }));
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/xml');

  // Instructing the Vercel edge to cache the file
  res.setHeader('Cache-control', 'stale-while-revalidate, s-maxage=3600');

  // generate sitemap here
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/</loc>
    <lastmod>2023-03-01</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.7</priority>
  </url>
    ${urls
      .map((url) => {
        return `
        <url>
          <loc>${url.loc}</loc>
          <lastmod>${url.lastmod}</lastmod>
          <changefreq>daily</changefreq>
          <priority>0.7</priority>
        </url>
      `;
      })
      .join('')}
  </urlset>`;

  res.end(xml);
}

For this website I am using Apollo Client and graphql to fetch the data, since that is what this project is built with. However you should use whatever it is you’re using for your server and request the data. If your using rest simply make a fetch request and get your blogs. You can also utilize Prisma ORM and not use APIs altogether since it’s a very popular stack mixed with Nextjs.

Generate Build

Next you will need to generate build. It’s time to export your Next.js app as a set of static files. This is so that you can deploy your app. To do this, you will need to update your build script inside the “package.json” file to include “next export.” The updated build script should look like this:

Once you’ve made these updates, run the build command again in your project directory:

npm run build

And that’s it! Your Next.js app is now supercharged with a sitemap, which will help improve your SEO.