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.
Read – 5 Best Nextjs MDX Blog Starters
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
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.
This NextJS feature is far better than coding it from scratch for rendering .xml file.