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

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

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

Error 404 occurred when trying to access the webpack file at my website address through next js

Check out my website at https://i.stack.imgur.com/i5Rjs.png I'm facing an error here and can't seem to figure it out. Interestingly, everything works fine on Vercel but not on Plesk VDS server. Visit emirpreview.vercel.app for comparison. ...

"Encountering a 404 error while attempting to forward to an HTML

I've been encountering an issue while trying to transition from a JSX page to an HTML page. Every time I attempt to do so, I receive a 404 error stating that the page doesn't exist. It's puzzling because it is clearly present in my files and ...

We regret to inform you that an application error has occurred: a critical server-side exception has been encountered during the deployment of the next app. For further details, please refer to the

Seeking assistance urgently! I am facing a recurring error when attempting to deploy my latest app on Vercel. Despite a successful build and deployment of the site, an error persists on the page. The environment variables appear to be correct. Interestingl ...

Unit Testing Angular: Passing FormGroupDirective into a Function

I am currently writing unit tests for a function that takes a parameter of type FormGroupDirective. I have been able to test most of the logic, but I'm unsure about what to pass as a parameter when calling the resetForm() function. Here is the code sn ...

Emphasize the text based on the content in Angular

database of customers check customer records customer service module access service details component for user details display view user details component 1 view user details component 2 template file for user details component see HTML template Seek ...

Obtaining images from the backend within a component's TypeScript file in a MEAN stack application is a

In my component.ts file, I am looking to retrieve images from the backend/images folder as Image objects. The paths of these images are stored in the database. this.productsService.getProduct(this.editId).subscribe(productData => { this.name = prod ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

How can Next-auth handle redirection for 401 errors?

Currently, I am utilizing Next-auth in combination with rtk query. My goal is to configure the application so that whenever a request results in a 401 unauthorized error, the page will automatically redirect to the login page. How can this be achieved? I ...

Having trouble updating the value in the toolbar?

Here is an example that I added below: When I click the add button, the value of the "newarray" variable is updated but not reflected. I am unsure how to resolve this issue. This function is used to add new objects: export class AppComponent { ne ...

Exploring Real-Time Typescript Validation in Next.JS

Checking for TypeScript errors in Next.JS can only be done with npm run build (or yarn build). Unfortunately, running npm run dev won't display TypeScript errors, which is quite inconvenient as it would be better to have them visible in the Terminal ...

Guide to displaying loading progress during server response delay in React with TypeScript

I need to find a way to update the loading state to false once the server responds. The challenge is that the response occurs in one component, while the progress bar is located in another. To illustrate the scenario: const Form: React.FC = () => { ...

What is the best way to handle and access exceptions thrown by Nestjs on the frontend?

In the process of creating a backend API using Nestjs, I am looking to retrieve exceptions from the frontend. For instance, in the login endpoint, if a user enters a non-existent email, the following code snippet is used: const user = await this.userModel ...

Enhanced Autocomplete Feature with Select All Option in MUI

Currently, I am utilizing Material UI (5) and the Autocomplete component with the option for multiselect enabled. In addition, I am implementing the "checkbox" customization as per the MUI documentation. To enhance this further, I am attempting to incorpor ...

Search for the booking object based on the user in MongoDB

In my Next.js app, I have 2 models - Booking and User. The object below represents a booking object. When a user books some dates, a new object is created in the bookings model. On the booking details page, users should be able to see details of their book ...

What is the best way to eliminate the # symbol in angular 5 URLs?

Currently, I am working on a project in Angular 5 and I need to remove the hash symbol (#) from my URL. The current URL looks like this: http://localhost:4200/#/product/add. While it works fine after being published on my domain, I encounter a 404 error ...

Over-reliance on the use of the useTranslation() hook

Currently, I am implementing next-i18next for translating my Next.js pages. I am contemplating whether using const { t } = useTranslation('common') in every react component would potentially impact performance negatively. Another option is to cal ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...