NextJs 13 unveils its cutting-edge dynamic sitemap feature

I am currently working on implementing a dynamic sitemap for NextJs 13.4.6, referring to the guide available at .

However, I have encountered an issue with the code provided towards the end of the article which is supposed to generate a sitemap for NextJS versions 13.3 and above, but unfortunately, it does not seem to work as expected.

The code snippet I am using aims to create a sitemap by retrieving URLs based on my website's routes and blog posts retrieved from our CMS via API calls.

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

// The root URL will be updated once in production
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);
  }
}

My concern lies in the fact that even after following the instructions diligently, visiting localhost:3000/sitemap.xml results in a 404 page, indicating that XML formatting has not been defined anywhere in the code.

If anyone has successfully implemented a dynamic sitemap for newer versions of NextJs13 or can provide examples demonstrating how to achieve this, your guidance would be greatly appreciated.

Thank you!

Answer №1

Consider substituting URL with the constant 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];

Please let me know if this adjustment works.

Answer №2

sitemap.ts file needs to be located within the app folder.

After that, proceed to compile the application by running:

npm run build

Once the build is complete, start the application using:

npm run start

https://i.sstatic.net/abc123.png

Answer №3

After struggling with an issue, I finally discovered that the root cause was a basePath defined in my next.config.js file that I hadn't incorporated into my request. Once I updated my request URL to include the basePath, the sitemap generation function started working perfectly, serving at /{basePath}/sitemap.xml and remaining dynamic post-launch without requiring manual regeneration at build time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

Combine TypeScript files in a specific sequence following compilation

I am hoping to utilize gulp for the following tasks: Compiling TypeScript to JavaScript, which is easily achievable Concatenating JavaScript files in a specific order, proving to be challenging Since I am developing an Angular application, it is crucial ...

Encountering deployment issues with a NextJS application using Docker following an upgrade from version 13.4.13 to version 13.4.15

After upgrading my NextJS application from version 13.4.13 to version 13.4.19, I encountered an error on Cloud Run stating: ERROR: (gcloud.run.services.update) Revision 'devrel-demos-00085-yaf' is not ready and cannot serve traffic. The user-pro ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

The transformation of href to data-href is now complete

Recently, I encountered an unusual issue in my Next JS application. I included Google Fonts using the code snippet below: <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500&family=Source+Serif+Pro:wght@300;400;500& ...

Expanding the range of colors in the palette leads to the error message: "Object is possibly 'undefined'. TS2532"

I am currently exploring the possibility of adding new custom colors to material-ui palette (I am aware that version 4.1 will include this feature, but it is a bit far off in the future). As I am relatively new to typescript, I am finding it challenging t ...

What is the code to continuously click on the "Next" button in playwright (typescript) until it is no longer visible?

Currently, I have implemented a code that clicks the next button repeatedly until it no longer appears on the pagination. Once the last page is reached, I need to validate the record. The problem arises when the script continues to search for the locator ...

Retrieving the original state value after updating it with data from local storage

Incorporating the react-timer-hook package into my next.js project has allowed me to showcase a timer, as illustrated in the screenshot below: https://i.stack.imgur.com/ghkEZ.png The challenge now lies in persisting the elapsed time of this timer in loca ...

Is there a way for me to retrieve the header values of a table when I click on a cell?

I have a project where I am developing an application for booking rooms using Angular 2. One of the requirements is to be able to select a cell in a table and retrieve the values of the vertical and horizontal headers, such as "Room 1" and "9:00". The data ...

Leverage the TypeScript compiler's output from a .NET library within a Blazor application by referencing it

I am currently facing an issue with three different levels: Main Issue: I have developed a Blazor WebAssembly (WASM) application that requires JavaScript, but I prefer to use TypeScript. To address this, I have added a tsconfig file and the TypeScript cod ...

Explore the next page on the API response by navigating to another page

In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server. import Router from 'next/router'; export const postAPI = async ( endpoint, data = {}, headers = {}, method = 'POST&apos ...

Ways to incorporate a language switcher with next-intl

"use client"; import { useLocale } from "next-intl"; import { locales, localeNames } from "../../i18nconfig"; import { useRouter } from "next/router"; import Link from 'next/link'; import { Fragment } from ...

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Exploring the distinctions between types and classes through type hinting

It seems that I am facing some challenges with this task and the reason is unclear to me switch (typeof request) { case 'EnrollmentRequest': The type '"EnrollmentRequest"' cannot be compared to the type '"string" | "number" | ...

Adding an item to a list using the PATCH method in Angular 7

Can anyone provide guidance on how to implement the PATCH method for manipulating an array within another array? ItemClass: export class ItemClass { constructor(public person: string, public name: string, public quantity: number, public price: number){} ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...