skip to Main Content

I am following this guide to create a dynamic sitemap for NextJs 13.4.6 https://claritydev.net/blog/nextjs-dynamic-sitemap-pages-app-directory

The issue I am having is the bottom of the article is where it has the code to do with a sitemap for NextJS versions of 13.3 and above – however, it does not work.

This is the code for my sitemap to return an object of URLs based on my routes and blog posts from cms (I am getting the blog post data from our API).

interface ApiResponseEntries {
  data: TransformedEntry[];
  status: number;
}

// This will change when we have a production URL
const rootUrl = "http://localhost:3000";

export default async function sitemap() {
  try {
    const url = "/api/routes/contentful/entries";

    const response: AxiosResponse<ApiResponseEntries> = await axios.get(url);

    const blogPostEntries: TransformedEntry[] = response.data.map(
      (entry: TransformedEntry) => {
        return entry.contentType === "blogPost";
      }
    );

    const blogPosts = blogPostEntries.map((entry: TransformedEntry) => ({
      url: `${URL}/blog/${entry.id}`,
      lastModified: entry.updatedAt,
    }));

    const routes = ["/", "/blog"].map((route) => ({
      url: `${URL}${route}`,
      lastModified: new Date().toISOString(),
    }));

    return [...routes, ...blogPosts];
  } catch (error) {
    console.error("Error", error);
  }
}

The issue is unless I read the article wrong I do not understand how this is providing a sitemap for Google if I go to localhost:3000/sitemap.xml there is just a 404 page… which makes sense as I never anywhere defined anything being XML.

Does anyone know how for the newer version of NextJs13 to get this dynamic sitemap to return on that url endpoint? or can point to examples of how it’s been done.

Thanks!

2

Answers


  1. Try replacing URL with the const rootUrl.

    const rootUrl = "http://localhost:3000"
    
    const blogPosts = blogPostEntries.map((entry: TransformedEntry) => ({
          url: `${rootUrl}/blog/${entry.id}`,
          lastModified: entry.updatedAt,
        }))
    
    const routes = ["/", "/blog"].map((route) => ({
          url: `${rootUrl}${route}`,
          lastModified: new Date().toISOString(),
        }));
    
    return [...routes, ...blogPosts];
    

    let me now if it works

    Login or Signup to reply.
  2. sitemap.ts file should be in the app directory.

    Then you have to build the app.

    npm run build
    

    and then run

    npm run start
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search