Create Sitemap In NextJS App Router Blog

Jan 21, 2024


Earlier it was little complicated to create a sitemap in NextJS with Page Router.

But with the App Router it is really easy to create a sitemap for your Blog or NextJS Project.

Follow these steps to easily create a sitemap in NextJS Project.

  1. Create a sitemap.js or sitemap.tsx file in your app directory
  2. Fetch your API
  3. Map through each link and return
  4. NextJS will automatically create a sitemap
  5. You don’t have to worry about anything like XML rendering

Read – 5 Best Nextjs MDX Blog Starters

1. Create sitemap.js

You have a file structure something like this. Create sitemap.js in app directory.

app
  |about
  |api
  |global.css
  |favicon.ico
  |layout.js
  |page.js
  |sitemap.js <---------- create sitemap.js or .tsx for typescript
public
  |next.svg
package-lock.json
README.md
package.json
next.config.mjs

2. Fetch API

Fetch your API & Map through it.

import { getAllPosts } from "@/lib/fetchData";

export default async function Sitemap() {
  const data = await getAllPosts();

  const posts = data.map((post) => ({
    url: `https://fronttt.com/${post.slug}`,
    lastModified: post.modified,
  }));

  return [
    {
      url: "https://fronttt.com/",
      lastModified: new Date(),
    },
    {
      url: "https://fronttt.com/about",
      lastModified: '2024-01-20T09:45:56.011Z',
    },
    {
      url: "https://fronttt.com/privacy-policy",
      lastModified: '2024-01-20T09:45:56.011Z',
    },
    ...posts,
  ];
}

Before returning dynamic sitemap links you can also return static links like contact us and about us page.

Conclusion

This NextJS feature is far better than coding it from scratch for rendering .xml file.