Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
YouTube Security VideosAnonymous Official: I'm begging you to understand this..(20.09.2026 um 21:30 Uhr)
Sichere ProgrammierungHow to Monitor Cron Jobs with a Simple HTTP Health Check(20.09.2026 um 23:14 Uhr)
Sichere ProgrammierungWhy my builds don't run on my laptop(20.09.2026 um 23:15 Uhr)
Sichere ProgrammierungDesigning offline-first when there's no server(20.09.2026 um 23:16 Uhr)
Sichere ProgrammierungSearching for Better Game Recommendations with Jev(20.09.2026 um 23:19 Uhr)
Linux Tipps & HardeningUbuntu 26.10 stops low memory from killing your desktop session(20.09.2026 um 19:55 Uhr)
YouTube Security VideosAnonymous Official: I'm begging you to understand this..(20.09.2026 um 21:30 Uhr)
Sichere ProgrammierungHow to Monitor Cron Jobs with a Simple HTTP Health Check(20.09.2026 um 23:14 Uhr)
Sichere ProgrammierungWhy my builds don't run on my laptop(20.09.2026 um 23:15 Uhr)
Sichere ProgrammierungDesigning offline-first when there's no server(20.09.2026 um 23:16 Uhr)
Sichere ProgrammierungSearching for Better Game Recommendations with Jev(20.09.2026 um 23:19 Uhr)
Linux Tipps & HardeningUbuntu 26.10 stops low memory from killing your desktop session(20.09.2026 um 19:55 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Generate Dynamic Sitemap in Next js

Reagiere als Erste:r — dein Feedback zählt!

Indroduction
In this blog, we'll explore how to dynamically generate a sitemap in Next.js to enhance your website’s SEO and keep the sitemap updated as your content changes.

Next JS
Next.js is a powerful React framework that offers developers several key features for building scalable and optimized web applications. With features like server-side rendering (SSR), static site generation (SSG), and API routes, Next.js allows developers to create high-performance websites with ease. The framework is also known for its file-based routing system and easy integration with popular tools, making it a popular choice for modern web development.

What is a sitemap and why?
A sitemap is a file that lists all the important URLs of your website, making it easier for search engines like Google to crawl and understand the structure of your site. Sitemaps can also include additional metadata like when a page was last updated, how frequently it changes, and its importance relative to other pages on the site. By generating a dynamic sitemap in Next.js, you ensure that your sitemap automatically reflects any new content, such as blog posts or dynamic routes, keeping search engines up to date and boosting your website's SEO.

How to create?
Create a sitemap.ts or js file in your next js app directory.

Folder structure

Create and export a function named sitemap.

export default function sitemap() {

}

Create one more function to fetch all routes created in your project.

import fs from "fs";
import { MetadataRoute } from "next";
import path from "path";

const baseUrl = process.env.SITE_URL || "http:localhost:3000";
const baseDir = "src/app";
const excludeDirs = ["api", "fonts"];

export const revalidate = 3600 // revalidate at most every hour


async function getRoutes(): Promise<MetadataRoute.Sitemap> {
  const fullPath = path.join(process.cwd(), baseDir);
  const entries = fs.readdirSync(fullPath, { withFileTypes: true });
  let routes: string[] = ["/"];

  entries.forEach((entry) => {
    if (entry.isDirectory() && !excludeDirs.includes(entry.name)) {
      routes.push(`/${entry.name}`);
    }
  });

  return routes.map((route) => ({
    url: `${baseUrl}${route}`,
    lastModified: new Date(),
    changeFrequency: "weekly",
    priority: 1.0,
  }));
}

In the above code block baseDir is the directory where your routes are created that will be mostly app/src. excludeDirs are used to specify which are the directories that need to be excluded while creating our routes array. routes array is the array that includes all our route's names. For eg: ["about", "blog"]

This code will create a sitemap for all static pages. But what if we have dynamic pages like todo/:id? For this, we need to fetch our dynamic data and make its route here, and append it to the routes array. The below function will do that job.

  // to create dynamic routes.
  async function getBlogs() {
    const data = await fetch("https://jsonplaceholder.typicode.com/todos");
    const todos = await data.json();
    console.log(todos, "todos");
    const todoRoutes: string[] = todos.map(
      (todo: any) => `/todo/${todo.id}`
    );
    routes = [...routes, ...todoRoutes];
  }

Now we need to call the getRoutes function from the sitemap function that we created in the beginning. Below is the entire code for the process.

import fs from "fs";
import { MetadataRoute } from "next";
import path from "path";

const baseUrl = process.env.SITE_URL || "http:localhost:3000";
const baseDir = "src/app";
const excludeDirs = ["api", "fonts"];

export const revalidate = 3600 // revalidate at most every hour


async function getRoutes(): Promise<MetadataRoute.Sitemap> {
  const fullPath = path.join(process.cwd(), baseDir);
  const entries = fs.readdirSync(fullPath, { withFileTypes: true });
  let routes: string[] = ["/"];

  entries.forEach((entry) => {
    if (entry.isDirectory() && !excludeDirs.includes(entry.name)) {
      routes.push(`/${entry.name}`);
    }
  });

  // to create dynamic routes.
  async function getBlogs() {
    const data = await fetch("https://jsonplaceholder.typicode.com/todos");
    const todos = await data.json();
    console.log(todos, "todos");
    const todoRoutes: string[] = todos.map(
      (todo: any) => `/todo/${todo.id}`
    );
    routes = [...routes, ...todoRoutes];
  }

  await getBlogs();

  return routes.map((route) => ({
    url: `${baseUrl}${route}`,
    lastModified: new Date(),
    changeFrequency: "weekly",
    priority: 1.0,
  }));
}

export default function sitemap() {
  return getRoutes();
}

Now run the project using

npm run dev

and go to *http://localhost:3000/sitemap.xml * There you can see a XML file that includes the the route names and other options that you set for generating the sitemap.

Generated sitemap.xml file

This post will guide you through creating a dynamic sitemap in Next.js. The logic presented here is tailored to my specific use case, but feel free to adapt it as needed. If you encounter any issues or have suggestions, please don't hesitate to leave a comment. I'm always open to feedback and improvement. Thank you for taking the time to read this!

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Generate Dynamic Sitemap in Next js

Thematisch verwandte Begriffe: Generate, Dynamic, Sitemap, Next · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-93956 | A flaw has been found in olivier-ls PHP-FTS up to 1.1.2. Affected by thi…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick