Avoid running getStaticPaths for a specific locale

Is there a way to prevent Next.js getStaticPaths from generating static pages for a specific locale?

In my Next.js configuration:

  i18n: {
    locales: ['default', 'en', 'hu', 'de', 'cz', 'eu', 'sl'],
    defaultLocale: 'default',
    localeDetection: true,
  },

We always need the locale, which is not supported by Next.js by default. To work around this, we have to use the middleware trick as described in the official Next.js documentation: https://github.com/vercel/next.js/discussions/18419

However, I do not want Next.js to generate pages like:

  • /default/products/id1
  • /default/products/id2

How can I prevent this behavior? The current method I tried with slice is not working:

 locales.slice(1).map((locale) => {
        pages.map((item) => {
          item.data.mainTabList?.[locale]?.map((main, mainidx) => {
            main.subTabList?.map((sub, subidx) => {
              questions.map((help) => {
                help.data.helplist?.[locale]?.map((title) => {
                  const urllink = {
                    maincategory: urlConverter(main.tab),
                    subcategory: urlConverter(sub.tab),
                    help: title.url
                  }
    
                  routes.push(urllink)
                })
              })
            })
          })
        })
      })

  const paths = routes.map((doc) => ({
    params: {
      maincategory: `${doc.maincategory}`,
      subcategory: `${doc.subcategory}`,
      help: doc.help?.toLowerCase(),
    },
  }))

I need help in finding a solution to prevent the generation of /default pages, as this is just a workaround for my locale prefix and will not be used anywhere.

Answer №1

To specify the locales for which getStaticPaths generates paths, you can return the desired locales in the paths array.

According to the i18n Dynamic Routing documentation:

If you are using getStaticProps with Dynamic Routes for your pages, you need to return all locale variants of the page that you want to prerender from getStaticPaths. In addition to the params object for paths, you should also include a locale field to specify which locale to render.


In your situation, your getStaticPaths function should resemble the following code snippet.

export const getStaticPaths = ({ locales }) => {
    // Your logic here
    
    // Exclude the `default` locale and iterate over the remaining locales
    locales.filter((locale) => locale !== 'default').map((locale) => {
        pages.map((item) => {
            item.data.mainTabList?.[locale]?.map((main, mainidx) => {
                main.subTabList?.map((sub, subidx) => {
                    questions.map((help) => {
                        help.data.helplist?.[locale]?.map((title) => {
                            const urlLink = {
                                maincategory: urlConverter(main.tab),
                                subcategory: urlConverter(sub.tab),
                                help: title.url,
                                locale // Include the current `locale` value in the `paths` array
                            }
                            routes.push(urlLink)
                        })
                    })
                })
            })
        })
    })

    const paths = routes.map((doc) => ({
        params: {
            maincategory: `${doc.maincategory}`,
            subcategory: `${doc.subcategory}`,
            help: doc.help?.toLowerCase(),
        },
        locale: doc.locale // Pass the `locale` value here
    }))

    return {
        paths,
        fallback: false
    }
}

Answer №2

According to the official guidelines on getStaticProps:

For static pages using getStaticProps that are not dynamic, a version is created for each language as mentioned above. getStaticProps is invoked with each language that needs to be displayed.

If you wish to exclude a specific language from being pre-rendered, you can add notFound: true in getStaticProps which will prevent that version of the page from being generated.

export async function getStaticProps(ctx: GetStaticPropsContext) {
  if (ctx.locale === 'none') { // or check "default"
    return {
      notFound: true,
    }
  }

  return {
    props: {},
    revalidate: 3600,
  }
}

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

Storing a MySQL query result in a global array in a Node.js environment

Just diving into the world of Node.js and Express, I'm trying to wrap my head around asynchronous functions and global variables. Specifically, I'm working on connecting to a MySQL database, fetching query results, and displaying them on a test.h ...

Remove any errors as soon as the input field becomes valid

My current setup involves AngularJS with node.js. To handle errors, I have devised the following strategy: node router effect.js: router.post('/', function(req, res, next){ req.checkBody('name', 'Eff ...

conceal menu upon click (gradually disappear)

This is a basic HTML/CSS menu. Currently, it is functioning properly for page redirection (href). However, I would like it to hide after being clicked on. I plan to call a function that will initiate an AJAX request upon clicking. Here is the code on JS ...

"Refreshing the page with Next.js version 13.5 by clicking on the link

import Link from "next/link"; import React from "react"; const Navbar = () => { return ( <div> <ul className="flex m-10 gap-10"> <Link href="/"> <li>Home< ...

What are the steps for implementing ABI in Next.js?

Challenge I'm currently working on a project using Next.js and the ZKSwap API, but I'm struggling to understand how to utilize the ABI of the smart contract that has been deployed. Specifically, my goal is to invoke the DepositETH function. It ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...

Highcharts JS encountered an error: x[(intermediate value)(intermediate value)(intermediate value)] is not a valid constructor

I'm in the process of creating a bar chart by fetching options from an ajax response. However, I encountered an error when passing the object to the highcharts constructor. Uncaught TypeError: x[(intermediate value)(intermediate value)(intermediate v ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

The functionality of the onclick button input is not functioning properly in the Google

Here is some JavaScript code: function doClick() { alert("clicked"); } Now, take a look at this HTML code: <div > <table border="2" cellspacing="0" cellpadding="0" class="TextFG" style="font-family:Arial; font-size:10pt;"> <tr> <t ...

Exploring TingoDB: Trouble encountered when passing global variable to insert operation

During my testing and benchmarking of several embedded databases using node.js, I have encountered an interesting issue with TingoDB. Does anyone have insight into why the following code snippet works as expected: var test = { hello:'world' }; f ...

Ways to forward a parameter to a different web address?

Is there a way to properly redirect a parameter such as http://example.com/?link=https://google.com to its destination at ? ...

Displaying a random number triggers a snackbar notification in a ReactJS application

Currently, I am utilizing the notistack package to display a snackbar on the screen. However, when calling the Snack component with enqueuesnackbar, a random number is displayed along with the snackbar. I'm looking to eliminate this random number fro ...

What are the steps to set up i18next in my HTML?

I have a project using nodejs, express, and HTML on the client side. I am looking to localize my application by incorporating i18next. So far, I have successfully implemented i18next on the nodejs side by requiring it and setting it up. var i18n = require ...

Exploring the integration of JSONP with the unmatched features of Google

I am attempting to utilize the Google maps directions API by using jquery $.ajax. After checking my developer tools, it seems that the XHR request has been completed. However, I believe there may be an issue with the way jquery Ajax handles JSON.parse. Y ...

Revamp the code by implementing promises

Upon calling the code snippet below, the two Webtrends calls are getting cancelled instead of returning an HTTP 200 status. This happens because the form submission triggers the cancellation. To resolve this issue, I introduced a 2-second delay before subm ...

The Google Maps directions stay visible even when new routes are generated

Utilizing the Google Maps Javascript API V3 in my Android WebView has presented a new issue. When I request directions from point A to B, it displays correctly. However, when I switch the endpoints to go from A to C, the route from A to B does not disappea ...

Displaying an iframe in Internet Explorer

My current setup involves a button that triggers the loading and printing of a report within an "invisible" iframe enclosed in a div. This process allows users to print the report from a different page without any visual disruption or changing pages, aside ...

In my React.js project, I am looking to iterate through an array of objects and organize them based on a specific condition

Here is an example of the structure of my JSON file: { "PlanetIdentifier": "KOI-1843.03", "TypeFlag": 0, "PlanetaryMassJpt": 0.0014, "RadiusJpt": 0.054, "PeriodDays": 0.176891 ...

The following middleware fails to transmit cookies received from the server

After a successful login to my Django backend, an httpOnly cookie is returned which is necessary for accessing protected routes in the Next app. To manage this, I have implemented a middleware that checks if a user is trying to access a protected route. If ...

Error in Next.js Image Component: Missing SRC

Encountering an error with the next.js image component, specifically related to a missing "src" property. Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Th ...