Generate the sitemap.xml file for a site
seo-in-nextjs can generate the sitemap.xml file for your Next.js site with automatic route detection.
Enabling sitemap.xml generation
Section titled “Enabling sitemap.xml generation”-
Create a
sitemap.tsorsitemap.jsfile to your project’s app folder. -
Import the
sitemapXmlfunction into the file.app/sitemap.ts import type { MetadataRoute } from "next";import { sitemapXml } from "@dlcastillop/seo-in-nextjs";export default async function sitemap(): Promise<MetadataRoute.Sitemap> {return sitemapXml();}app/sitemap.js import { sitemapXml } from "@dlcastillop/seo-in-nextjs";export default async function sitemap() {return sitemapXml();} -
Open http://localhost:3000/sitemap.xml in your browser to see the sitemap.
Manual routes
Section titled “Manual routes”Automatic route detection works by analyzing your project’s file system. However, not all routes in a Next.js application are explicitly represented in the file system.
To include these routes in your sitemap, you need to manually specify them in the manualRoutes property of the seo.config.ts or seo.config.js file.
import { defineSeoConfig } from "@dlcastillop/seo-in-nextjs";
export default defineSeoConfig({ baseUrl: "https://example.com", siteName: "Example", defaultOgImg: "/og-default.png", manualRoutes: ["/users/1", "/users/2", "/users/3"],});In the manualRoutes property you must include:
- Dynamic segments: Routes with parameters like
/users/[id],/posts/[slug] - Catch-all routes: Routes using
[...slug]or[[...slug]]syntax - Parallel routes: Routes defined with
@folderconvention - Intercepting routes: Routes using
(.)folderor(..)foldersyntax - Programmatically generated routes: Routes created at runtime or build time
- Data-driven routes: Routes that depend on database, CMS, or API content
Advanced sitemap configuration
Section titled “Advanced sitemap configuration”By default, sitemapXml() generates a basic sitemap with all detected and manual routes. However, you can customize each route’s metadata by passing a configuration array to the function.
The configuration allows you to specify additional properties for each route, such as modification date, priority, change frequency, and more.
import type { MetadataRoute } from "next";import { sitemapXml } from "@dlcastillop/seo-in-nextjs";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> { return sitemapXml([ { route: "/", lastModified: new Date(), changeFrequency: "daily", priority: 1, }, { route: "/about", lastModified: new Date("2024-01-15"), changeFrequency: "monthly", priority: 0.8, }, ]);}import { sitemapXml } from "@dlcastillop/seo-in-nextjs";
export default async function sitemap() { return sitemapXml([ { route: "/", lastModified: new Date(), changeFrequency: "daily", priority: 1, }, { route: "/about", lastModified: new Date("2024-01-15"), changeFrequency: "monthly", priority: 0.8, }, ]);}Related
Section titled “Related”View related API references.