Creating sitemaps on Next.js using next-sitemap is not supported

Creating dynamic sitemaps for my Next.js site using next-sitemap has hit a snag.

Following the documentation, I've implemented the following code:

//pages/server-sitemap-index.xml/index.js
import axios from "axios";
import { getServerSideSitemapIndex } from "next-sitemap";

export const getServerSideProps = async (ctx) => {
  const res = await axios(`${process.env.API_ROOT}/books`);
  const { data } = res.data;
  const fields = data.map((item) => ({
    loc: `${process.env.NEXTAUTH_URL}/${item.slug}`,
    lastmod: item.updatedAt,
    priority: 0.7,
    changefreq: "daily",
  }));

  console.log({ fields });
  return getServerSideSitemapIndex(ctx, fields);
};

export default function SitemapIndex() {}

The console.log in the code above produces the expected output:

{
  fields: [
    {
      loc: 'http://localhost:3000/The-river-between-3pgkgy',
      lastmod: '2022-03-16T16:02:06.000Z',
      priority: 0.7,
      changefreq: 'daily'
    },
    {
      loc: 'http://localhost:3000/The-river-between-0tqwkgy',
      lastmod: '2022-03-16T16:02:06.000Z',
      priority: 0.7,
      changefreq: 'daily'
    },
    {
      loc: 'http://localhost:3000/The-river-between-tqwkgy',
      lastmod: '2022-03-16T16:02:06.000Z',
      priority: 0.7,
      changefreq: 'daily'
     }
  ]
}

However, when accessing

http://localhost:3000/server-sitemap-index.xml
, an issue arises:

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>[object Object]</loc>
</sitemap>
<sitemap>
<loc>[object Object]</loc>
</sitemap>
<sitemap>
<loc>[object Object]</loc>
</sitemap>
</sitemapindex>

The XML is not populating correctly. Could this be due to using JavaScript instead of TypeScript as shown in the documentation? Ps: Non-dynamic sitemaps are functioning as expected.

Answer №1

After some investigation, I have identified the root cause of the issue.

The key was to correctly import the specific module, as next-sitemap offers two distinct APIs.

import { getServerSideSitemapIndex ,getServerSideSitemap } from "next-sitemap";

It is crucial to utilize the getServerSideSitemap function for resolving this matter.

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

Regular expression in JavaScript that specifically matches numbers formatted in the style of JavaScript

My goal is to develop a javascript regular expression that specifically identifies valid Javascript-style numbers. The requirements entail accommodating an optional minus or plus sign before the number, recognizing the decimal dot, and supporting exponent ...

When populating data, two ID fields (_id and id) are generated as duplicates

Upon retrieving information from my database, I have noticed the presence of an additional id field alongside the standard _id field. These two fields consistently contain identical values. However, it seems that the id field appears only during population ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

I'm struggling to retrieve a specific column of data from a JSON file. Does anyone know how to do this successfully?

I have a JSON file with various columns, but I only want to display the rdid column. I am new to learning node and still trying to figure things out. data [ {"edid":"r7vr8r", "rdid":"86596", "rssi":&qu ...

Control the switch for CSS selectors

Consider the following scenario where CSS rules are defined: <style> table {background:red;} div {background:green;} </style> In addition, there is HTML code that calls a JavaScript function: <table onclick="tu ...

Problem with the getJSON function

Here is a question that has been bothering me: I am currently working on a barcode scanner script which retrieves data from a JSON file. The script itself functions properly, except for one issue. After the while loop, I want to display an error alert m ...

Automatic closing of multile- vel dropdowns in Bootstrap is not enabled by default

I have successfully implemented bootstrap multilevel dropdowns. However, I am facing an issue where only one child is displayed at a time. <div class="container"> <div class="dropdown"> <button class="btn btn-default dropdown-to ...

What could be the reason for TreeView failing to load in an Angular application?

Attempting to design a TreeView with drag and drop features, I am utilizing the plugin . A demonstration can be accessed here: Despite following the documentation instructions, my TreeView fails to load - what could be the issue? Below is the code snipp ...

Transform jQuery UI Slider input into clickable links

Is there a way to turn the jQuery slider values into clickable links? For example, if the slider is at 1920, can it redirect the user to another page? I've included the code in a fiddle: http://jsfiddle.net/up6Bx/ Any assistance would be greatly app ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Generating prime numbers in Javascript

My attempt at generating the prime numbers less than 20 using my current knowledge is as follows: let arr = []; for (let x = 3; x <= 20; x++) { for (let i = 20; i > 0; i--) { if (x % i !== i) { arr.push(x) } } console.log(arr) ...

Route.get() function is expecting a callback function, but instead received a string object

Having searched through similar posts, I am unsure and lack the experience to apply the suggested resolutions to my project. I recently built a basic app with two main routes as part of a Udemy course, but I am struggling with the following error: "Route.g ...

Having trouble parsing the BODY of a NodeJs JSON post request?

I've been working on creating a basic API using nodeJS, but I've run into a problem while trying to post data. Below is my app.js file: const express = require('express'); const feedRoutes = require('./routes/feed'); const ...

Activate only one option group at a time

<select name="location"> <optgroup label="West Coast"> <option value="1">Los Angeles</option> <option value="2">San Francisco</option> <option value="3">Seattle</option> &l ...

What is the best way to prevent code execution until a value is returned by $.get?

My attempt to read data from a file and store it in an array using jQuery's get function has hit a snag. Since the get function is asynchronous, the code that comes after the $.get call runs before the data is defined. How can I make sure that the cod ...

JavaScript/jQuery - dynamic name selector with animation

I've been working on developing a raffle ticket picking script using JS and jQuery. Initially, my script is functioning well. However, I am now looking to enhance its visual appeal so that it can be operated in assembly. In order to achieve this, I ...

Video playback disabled on hover in Chrome browser

I have added videos to a search results page. When the user hovers over the video, I want to show a preview of it in a separate container and start playing the video. $(".videoSearchResults video").mouseenter(function () { var container = document.cre ...

Aligning SVG shapes within each other

I recently encountered a scenario where I needed to position SVG shapes in the center of each other with varying scales. For instance, placing a rectangle or triangle within the center of a circle. While I found some solutions that worked for shapes like ...

Looking for a comprehensive calculation that takes into account various input values?

I need to display the List Price at the bottom of the form so users are aware of the cost to list their item. Within a php file, I have defined price brackets. For example, if the listing price is £150.00, it falls between £100 and £199.99 and thus nee ...

The strange behavior of !important, display:none, and .height()

While working with a piece of JS code yesterday, I stumbled upon something peculiar. There was a div element that was initially hidden using display:none, and I was utilizing its height in some JavaScript calculations. Everything was functioning properly u ...