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.

The ultimate vibe-coding starter kit

SupaLaunch boilerplate provides everything you need for vibe-coding SaaS with Cursor: Next.js, Supabase, Auth, Payments, Database, Storage, and more. Plus: Cursor Rules & Supabase MCP integration.

  • Cursor Rules & MCP included for seamless vibe-coding
  • Save weeks of your time: Auth, payments, emails, file storage & more ready to go
  • Focus on what matters: Spend your time building your product, not boilerplate code