Making Dynamic Sitemaps in Next.js 14

Tag: Front-end

Making Dynamic Sitemaps in Next.js 14

Your trusty guide to help you make your website discoverable easily by search engines!

Hello everyone! Today we'll be talking about sitemaps. Sitemaps are one of the important files for Search Engine Optimization, or SEO in short, so that search engines, and in the end, people, can discover your website! Now we'll be talking about Dynamic Sitemaps in React's framework Next.js, in this tutorial we will learn how to make dynamic sitemaps, for example where the dynamic sitemap is for a blog. So, let's begin!


First, in your app directory, make a file named sitemap.js. Inside the file, create the following function:


export default function sitemap() {

}


In the function, you will map two arrays, one with the dynamic URLs, and one with static URLs. Make sure you already imported the dynamic URLs in some way! In my case, my dynamic URLs are already imported.


import posts from "@/app/lib/posts"
export default function sitemap() {
const blogs = await posts();
const page = blogs.map(({ url, date }) => ({
url: `(your main site)/blog/${url}`,
lastModified: date,
}))

const routes = ["", "/portfolio", "/about", "/blog", "/search"].map((route) => ({
url: `(your main site)${route}`,
lastModified: new Date().toISOString(),
}))

return [...routes, ...page]

}


Make sure to adjust the parameters according to your data structure while mapping the array, and also the URL to your main site!


In conclusion, sitemaps are really important if you wish to improve the SEO of your website. With this dynamic sitemap, everytime there's a new page, it will automatically update itself to accomodate search engines. I hope this guide is helpful to you! See you later, and stay determined!