Generate a Dynamic Sitemap in Next.js with Prisma

A sitemap is essential for SEO, helping search engines index your website efficiently. In this blog, weโll explore how to create a dynamic sitemap in a Next.js project using Prisma to fetch URLs from a database.
Prerequisites
Before getting started, ensure you have the following setup:
A Next.js project
Prisma configured with your database
Blog data stored in the database with
slug
andupdatedAt
fields
Step 1: Install Dependencies
Make sure Prisma is installed in your project. If not, install it using:
npm install @prisma/client
If Prisma isnโt initialized in your project, set it up using:
npx prisma init
Step 2: Create the Sitemap Function
Next.js allows you to generate sitemaps dynamically by creating an API route or exporting an asynchronous function in the app/sitemap.ts
file (if using Next.js App Router).
Hereโs how you can create the dynamic sitemap function using Prisma:
import prisma from "@/lib/prisma";
export default async function sitemap() {
// Fetch blog URLs from the database
const blogPosts = await prisma.BlogPosts.findMany({
select: { slug: true, updatedAt: true },
});
console.log(blogPosts);
// Convert blog data to sitemap format
const blogSitemap = blogPosts.map((post) => ({
url: `https://yourwebsite/blogs/${post.slug}`,
lastModified: new Date(post.updatedAt || new Date()),
changeFrequency: "weekly",
priority: 0.5,
}));
return [
{
url: "https://yourwebsite/",
lastModified: new Date(),
changeFrequency: "yearly",
priority: 1,
},
{
url: "https://yourwebsite/blogs",
lastModified: new Date(),
changeFrequency: "weekly",
priority: 0.5,
},
...blogSitemap,
];
}
Explanation:
The
prisma.BlogPosts.findMany()
function retrieves all blog posts from the database, selecting theslug
andupdatedAt
fields.We map through the posts to generate URLs in sitemap format.
Additional pages (homepage, blogs page) are manually added with defined
changeFrequency
andpriority
values.
Step 3: Expose the Sitemap in Next.js
To make the sitemap available for search engines, modify the next.config.js
file to define the sitemap route:
module.exports = {
async rewrites() {
return [
{
source: '/sitemap.xml',
destination: '/api/sitemap',
},
];
},
};
Alternatively, create an API route at pages/api/sitemap.js
(for Pages Router):
import sitemap from "../../sitemap";
export default async function handler(req, res) {
const sitemapData = await sitemap();
res.setHeader("Content-Type", "application/xml");
res.write(generateSitemapXML(sitemapData));
res.end();
}
function generateSitemapXML(pages) {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pages
.map(
(page) => `
<url>
<loc>${page.url}</loc>
<lastmod>${page.lastModified.toISOString()}</lastmod>
<changefreq>${page.changeFrequency}</changefreq>
<priority>${page.priority}</priority>
</url>`
)
.join("")}
</urlset>`;
}
Step 4: Deploy and Test
Once the sitemap is set up, deploy your Next.js application and check if the sitemap is accessible via https://yourwebsite.com/sitemap.xml
.
You can also submit the sitemap URL to Google Search Console to improve indexing.
Conclusion
By implementing a dynamic sitemap in Next.js with Prisma, you ensure your website stays updated with the latest blog posts without manual intervention. This helps search engines index your content efficiently and improves SEO rankings.
๐ฅ Found this blog post helpful? ๐ฅ
If you enjoyed this article and found it valuable, please show your support by clapping ๐ and subscribing to my blog for more in-depth insights on web development and Next.js!
Subscribe here: click me
Your encouragement helps me continue creating high-quality content that can assist you on your development journey. ๐
Written by Sagar Sangwan
๐จโ๐ป Programmer | โ๏ธ Love Traveling | ๐ณ Enjoy Cooking | Building cool tech and exploring the world!
View more blogs by me CLICK HERE
Loading related blogs...
SUBSCRIBE to Newsletter
In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.