What is the best way to eliminate the locale string from the default language in Next.js sitemap?

I have set up my website to be displayed in both French and English languages. After building my sitemap, I noticed a issue with the URLs listed in my sitemap.xml. Instead of having:

/blog
/en-US/blog

I found that it displays as:

/fr-FR/blog
/en-US/blog

The presence of the fr-FR string in my sitemaps is causing duplication of pages, which can negatively impact SEO. How can I remove this string from my sitemaps? Additionally, how do I specify canonical pages in an XML format?

Below is my internationalization configuration:

i18n: {
    locales: ["fr-FR", "en-US"],
    defaultLocale: "fr-FR"
 }

This is what my getStaticPaths function looks like:

export async function getStaticPaths({ locales }) {

    const products = await fetchAPI(`/products`);
    const productsData = await products;

    const resProductsEn = await fetchAPI(`/products?${enTranslation}`);
    const productsDataEn = await resProductsEn;

    const paths = []

    productsData.map((product) => paths.push(
        { params: { slug : product.slug} }
    ))

    productsDataEn.map((product) => paths.push(
        { params: { slug : product.slug}, locale: 'en-US'}
    ))      
    
    return {
      paths,
      fallback: true
    };  
}

I am using next-sitemap to generate my sitemap - next-sitemap.config:

module.exports = {
    siteUrl: process.env.FRONT_END_URL,
    generateRobotsTxt: true, 
    exclude: [
        '/test', 
        '/commande', 
        '/forgotten-password', 
        '/reset-password',  
        '/panier', 
        '/mon-compte', 
        '/mon-compte/*',
        '/fr-FR',
    ],
    robotsTxtOptions: {
        additionalSitemaps: [
            `${process.env.FRONT_END_URL}/sitemap.xml`,
            `${process.env.FRONT_END_URL}/server-sitemap.xml`,
            `${process.env.FRONT_END_URL}/en-server-sitemap.xml`
        ]
    }  
}

For a more concrete example:

<url><loc>https://www.website.com/fr-FR/questions-reponses</loc><changefreq>daily</changefreq><priority>0.7</priority><lastmod>2021-12-03T18:26:08.673Z</lastmod></url>    
<url><loc>https://www.website.com/en-US/questions-reponses</loc><changefreq>daily</changefreq><priority>0.7</priority><lastmod>2021-12-03T18:26:08.673Z</lastmod></url>

Answer №1

To exclude the default locale from the generated paths, you can utilize the transform property within the next-sitemap.js file.

module.exports = {
    // Additional configuration for `next-sitemap.js` can be included here
    transform: async (config, path) => {
        return {
            loc: path.replace('/fr-FR', ''), // Remove `/fr-FR` from paths - consider making it dynamic by referencing i18n config
            changefreq: config.changefreq,
            priority: config.priority,
            lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
            alternateRefs: config.alternateRefs ?? []
        }
    }
}

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

AngularJS - removing the date value from the UI calendar

I have implemented the AngularJS ui-date feature and included the following html & js code :- <input id="dob" name="dob" ui-date="dateOptions" class="form-control" ui-date-format="dd-MM-yy" ng-model="user.dob" ng-required="true" readonly> $scop ...

What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully ...

The image from the local source displays correctly in the initial component without any issues, but it does not appear in its corresponding detail component

My blog has a component for displaying posts and another component for showing the details of a single post as seen below. A key point to note is that while the blog component can load and display images, the blog details component cannot. Why is this? h ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

Can anyone share best practices for writing unit tests for $scope.broadcast and $scope.$on in Jasmine?

Greetings, I am new to the AngularJs/NodeJs realm, so please bear with me if this question seems basic to some. Essentially, I have two controllers where the first controller broadcasts an 'Id' and the second controller retrieves that Id using $ ...

Preventing typing by detecting keypresses in a text input

I'm trying to set up a text input field so that it triggers a function when the Enter key is pressed. I currently have an if condition to check for the Enter key press, but this prevents users from typing in the input box. What should I include in the ...

Storing Checkbox Value and Name in an Array using React JS

I'm experiencing an issue with the checkbox. I need to capture the value and name data in array format for further processing. Checkbox Example: <input type="checkbox" id="Honda" name="A1" value="Honda" onCl ...

Guide to stopping available times from cycling through an array with the help of watch功能?

I am currently developing a booking application within Vue CLI. I have made use of vue-ctk-date-time-picker for selecting the date and time. My goal is to disable certain times based on the chosen date, but I am encountering an issue. The code I have writt ...

Unable to reach other documents within Node.js

NOTE: Although similar questions may exist on Stack Overflow, this one is unique. Please read carefully. I'm diving into Socket.io on Node for the first time, and I'm facing an issue in my HTML file where I cannot access other files like images. ...

Retrieve data from the table and dropdown menu by clicking a button

A script is in place that retrieves data from two columns (Members, Description) dynamically from the table upon button click. Table html Here is the JQuery code responsible for extracting values from the table: $(function() { $('#myButton') ...

Unable to access the 'singleton' property of an undefined value in Adonisjs

An issue arises when the tender attempts to register a Service of singleton type. My approach involves utilizing IocContract AppProvider export default class AppProvider { constructor( protected app: ApplicationContract, protected $container: I ...

JavaScript: Finding the current month and all subsequent months until the end of the year

Is there a way in vanilla JavaScript to retrieve the current month and the following 12 months? For instance, if today is April 2022, I would like the output to be: April 2022 May 2022 June 2022 July 2022 August 2022 September 2022 October 2022 November 2 ...

Logging on the client side with node.js without the need for additional modules

Do you think it's a good idea to wrap my minified JavaScript code in a try-catch block so that if a client-side error occurs, it sends a POST request to my server and appends the error to a log file on the server? The main concern here is security - ...

Ways to access and retrieve data from Vuex store values?

Combining vuex and vuejs 2 for the first time. I'm a beginner with vuex and I need to monitor changes in a store variable. Trying to implement the watch functionality within my vue component. This is my current code snippet: import Vue from ' ...

What is the best method for passing a JavaScript object to PHP using Ajax?

I have looked into similar questions like this and this, but none of them have helped me solve my issue. When I check the console log for my data, it displays the following: Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008" ...

Error encountered while trying to call callback functions

I encountered an error in my code, but I managed to resolve it independently. Could someone please provide an explanation of why the code wasn't working and delve into the mechanics behind the issue? Here is the code snippet: var listTables = functi ...

Transform a text with HTML tags into sentences while preserving the separators in Javascript

Here is a unique string with some embedded HTML code: This is the first sentence. In the second sentence, there is a <a href="http://google.com">Google</a> link! The third sentence may have an image like <img src="http://link.to.image.com/h ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

Rearrange table cells effortlessly with automatic saving functionality

I am currently working on manipulating a dynamically generated table that has content editable td elements. The database is updated using an AJAX call within this script. $(document).ready(function(){ $("td[contenteditable=true]").blur(function(){ v ...

The checkbox linked to a Vector layer in Openlayers 3 seems to have no effect on its visibility

Help me debug my code where I am attempting to connect a checkbox to a vector layer's 'visible' property. I can't seem to figure out what's wrong, can you spot the error? Interestingly, this code successfully works for ol.layer.Ti ...