How to create a Next.js 14 dynamic sitemap?

What is a sitemap?

A sitemap is a file that contains a comprehensive list of all the pages on a website, along with their interrelationships. It plays a crucial role in aiding search engines to efficiently crawl and comprehend the structure of the website. Sitemaps also offer vital information about each page, such as its last update and frequency of changes. Particularly for larger or intricately structured websites, having a sitemap simplifies the process for search engines to discover and index all pages. According to Google, sitemaps prove beneficial for new websites with limited external links and those with content that lacks sufficient interlinking. In any scenario, integrating a sitemap can enhance a website's SEO by furnishing valuable insights to search engines and improving overall site navigation.

Is it necessary for my website?

Imagine your blog as a big library, and a sitemap as a well-organized catalog that helps people find books easily. Now, think of this catalog as not just static but magically updating itself whenever a new book arrives or an old one gets a makeover. That's what a dynamic sitemap does for your blog in the vast world of the internet.

Let's say your blog is built using Next.js 14 – a cool tool to create and manage your online library. The blog posts are like the books on your shelves, and the sitemap is your digital librarian, making sure search engines (like Google) and visitors can easily find and explore your literary treasures.

Now, the traditional way would be to manually update this catalog every time you add or change a book – quite a tedious job! But with a dynamic sitemap, it's like having a magical librarian who does this for you in real time. Every new blog post you publish or update is instantly added to the catalog, making it a breeze for search engines to know about your latest content and for readers to discover it.

Setting up your Next.js 14 project is like building the shelves and organizing the initial catalog. Once that's done, you teach your digital librarian to not only list the fixed sections but also dynamically add the latest books. This is where the coding magic happens.

If you publish a new blog post, your sitemap automatically updates to include it. No need to manually tell the librarian about each new book – it's taken care of. This ensures that your library (blog) is always up-to-date, easily found by search engines, and provides a smooth reading experience for your visitors.

For instance, create a "sitemap.js" file in your app directory for dynamic generation.

import { getAllPosts } from "./queries";

const sitemap = async () => {
  const BASE_URL = "https://www.YOUR_DOMAIN.com/";

  const posts = await getAllPosts();

  const postURLS =
    posts?.length > 0
      ? (posts[1] || []).map((post) => ({
          url: `${BASE_URL}/blog/${post?.slug}`,
          lastModified: new Date(post?.publishedAt),
        }))
      : [];

  return [
    {
      url: BASE_URL,
      lastModified: new Date(),
    },
    {
      url: `${BASE_URL}/blog`,
      lastModified: new Date(),
    },
    ...postURLS,
  ];
};
export default sitemap;

You're done! Now you know how to generate it dynamically.

Conclusion:

In the end, this dynamic sitemap isn't just a technical detail, it's your secret weapon to make sure your blog stands out in the vast digital library of the internet, guiding both search engines and readers to the wonderful stories you have to share.


We at CreoWis believe in sharing knowledge publicly to help the developer community grow. Let’s collaborate, ideate, and craft passion to deliver awe-inspiring product experiences to the world.

Let's connect:

This article is crafted by Syket Bhattachergee, a passionate developer at CreoWis. You can reach out to him on X/Twitter, LinkedIn, and follow his work on the GitHub.

0
Subscribe to my newsletter

Read articles from Syket Bhattachergee directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Syket Bhattachergee
Syket Bhattachergee

🚀 Hey there, I'm Syket, a passionate Software Engineer with a love for crafting extraordinary solutions using the power of React, Next.js, Typescript, Express, and MongoDB. 🚀 🌟 With a focus on scalability and robustness, I embark on coding adventures that push the boundaries of what's possible. 🌟 📚 Lifelong learning is my mantra, and I thrive on mastering new technologies in record time. Whether it's learning the latest libraries or staying ahead of the curve with emerging trends, I'm always up for the challenge. 💡 🔧 Efficiency is my middle name, and I'm all about embracing automation to make our lives as developers smoother and more productive. Less time spent on repetitive tasks means more time for groundbreaking innovations. 💻 💡 A clean code advocate, I believe in the power of elegant solutions that are easy to maintain and delight to collaborate on. Let's create code that's not just functional but a masterpiece of art. 🎨 🤝 Building strong and trusting teams is my superpower. Leading with empathy, I thrive in collaborative environments where diverse perspectives create the most remarkable outcomes. Let's forge a team that's unstoppable. 🤝 🏆 When it comes to project completion, success is the only option. I'm a tenacious problem-solver, and I won't rest until our projects shine brightly with unparalleled achievements. 🏆 🌟 Let's connect and build something extraordinary together!