Blog

How to automatically generate a Sitemap for your NextJS app

4 Feb 2024
By Denis

NextJS Sitemap Generation Guide

NextJS is a great framework for building SEO-friendly web applications. It provides a lot of features out of the box that make it easy to optimize your app for search engines. In this guide, we'll cover how to add a sitemap to your NextJS app to improve its SEO and help search engines discover and index your content more efficiently.

What is a Sitemap?

A sitemap is a file that contains a list of all the pages on your website. It helps search engines discover and index your content more efficiently. For example, you can submit your sitemap to Google Search Console to let Google know about all the pages on your website.

Sitemap Example

Generate a Sitemap automatically with NextJS

NextJS provides a way to generate a sitemap for your app automatically.

To generate a sitemap for your NextJS app, you need to create file sitemap.ts (or sitemap.js for JavaScript) in the app directory and add the following code:

const urls = [
    '/',
    '/about',
    '/contact',
    '/blog',
]

export default async function sitemap() {
    const xmlUrls = urls.map(url => {
        return {
            url: `https://example.com${url}`,
            lastModified: new Date(),
        }
    })

    return xmlUrls
}

This code creates a list of URLs for your website and returns them in a format that can be used to generate a sitemap. Now, you can add all the URLs of your website to the urls array.

Your website sitemap will be generated automatically. It will be available at https://example.com/sitemap.xml. You can submit this URL to search engines to help them discover and index your content more efficiently.

Launch your SaaS with our Supabase + NextJS Course

Learn how to create an AI-powered SaaS from scratch using Supabase and Next.js. We will guide you from zero to launch. What you will learn:

  • Stripe payments
  • Authentication with email/password and social logins
  • AI functionality: Chat, Langchain integration, OpenAI API streaming and more
  • How to setup emails, file storage, etc.