Creating dynamic routes for custom locales in Next.js

I'm currently working on a Next.js application with internationalization functionality using next-i18next. Most of my site's pages have been generated in both English and French, except for dynamic routes (like blog/[id]/[blog-title]). For these dynamic route pages, only the English version is generated.

It's important to mention that the blog entries are identical in both languages. So if a user clicks on a blog entry from the list, they will see the same content regardless of language.

However, when a French-speaking user visits a page with a dynamic route, they encounter a 404 error. I'm relatively new to React and Next.js, so it's possible that I've overlooked something simple.

// next-i18next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr'],
    defaultLocale: 'en',
    localeDetection: true,
  },
}
//
// blog\[id]\[title] 
//
export async function getStaticPaths() {
  const response = await axios.get('https://api.myappi.com/blog')
  const posts = response.data

  const paths = posts.map((post: Props) => ({
    params: { id: post.Id, title: post.Title },
  }))  
 
  return { paths, fallback: false }
}

export async function getStaticProps(props: IStaticProps) {
  const { id, locale } = props.params
  const response = await axios.get(`https://api.myappi.com/blog/${id}`)
  const post = await response.data

  if (!post) {
    return {
      notFound: true,
    }
  }

  return {
    props: { 
      Id: post.Id,
      Title: post.Title,
      Blog: post.Blog,
      DatePosted: post.DatePosted, 
      PostedBy: post.PostedBy,
      ...(await serverSideTranslations(props.locale, ['common', 'blog']))
    }
  }
}

Answer №1

To ensure that dynamic routes are pre-generated properly, it is important to explicitly specify the locales that you want in the getStaticPaths function. Otherwise, Next.js will only generate pages for the default locale.

As per the Internationalized Routing documentation:

When using getStaticProps with Dynamic Routes, all desired page variants for different locales should be returned from the getStaticPaths function. In addition to the params object for paths, a locale field can be included to specify the rendering locale.

This requirement can be met by adjusting your getStaticPaths function to create paths for each combination of slug/locale.

export async function getStaticPaths({ locales }) { // Retrieve available locales from `context`
   const response = await axios.get('https://api.myappi.com/blog')
   const posts = response.data

   const paths = posts
       .map((post: Props) => locales.map((locale) => ({
           params: { id: post.Id, title: post.Title },
           locale // Specify locale here
       })))
       .flat() // Flatten array to avoid nested arrays
 
   return { paths, fallback: false }
}

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

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

In Vue(tify), transitions require children to have keys, but in this case, there are no tags present as children

Trying to implement a transition on a list using Vue and Vuetify, but encountering the error message vue.runtime.esm.js?2b0e:619 [Vue warn]: <transition-group> children must be keyed: <v-card> I attempted the Vuetify approach <v-fade-transi ...

Store JWT as a cookie in Vue JavaScript and ensure it is successfully saved before proceeding

Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home. However, there seems to be an issue with the authentication check on the /home route. When c ...

Using jQuery, you can create and add an element to the page when a user clicks

Currently, my webpage contains numerous anchor tags that link to various video files, along with a single div element: <a href="http://www.example.com/example-1.mkv" class="video">1</a> <a href="http://www.example.com/example-2.mkv" class=" ...

Autocomplete fails to recognize any modifications made to the original object

I am currently utilizing the jQuery library's autocomplete() method on a text input field, setting Object.getOwnPropertyNames(projects) as the source: $(function() { $("#project").autocomplete({source: Object.getOwnPropertyNames(projects)}); } B ...

Using Selenium WebDriver in JavaScript to Extract Text from an Array

During my experimentation with Selenium webdriver in javacript, I encountered a challenge when trying to extract text from an array of WebElements (specifically cells within a table). The usual command getText() did not work as expected when attempting to ...

Exploring the Power of Pengines in Combining Prolog with Javascript

I'm currently working on an artificial intelligence project that utilizes Prolog, and I'm looking to publish it online. I came across pengines (http://pengines.swi-prolog.org/docs/documentation.html, http://www.swi-prolog.org/pldoc/doc_for?object ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

I'm currently attempting to incorporate the Material-UI InfoIcon into my code, but I'm unsure of how to properly integrate it within a TextField component

I am attempting to integrate the Material-UI InfoIcon into my TextField code, but I'm unsure of how to go about it. Here is the snippet of Material-UI code: <InfoIcon fontSize="small" /> This is where I would like to place it: <Grid item ...

Exploring the enhanced capabilities of FeathersJS by integrating express-babelify-middleware

Attempting to integrate express-babelify-middleware with FeathersJS, an error message appears in the browser console: The error reads: ReferenceError: main_run is not defined This indicates that babelify may not be functioning correctly or I might be u ...

How to format numbers in JavaScript post calculations

Struggling to find a solution to format calculation results with commas for thousand separators (e.g., 10,000). After implementing the .toLocaleString('en-US', {maximumFractionDigits:1}); method to format numbers in the output, I encountered unex ...

After being initialized, the added Vue.js DOM elements do not function together

I updated an HTML page with ajax contents and incorporated Vue.js for front-end events. Unfortunately, the dynamically added elements are not interacting with the Vue.js instance, even when I attempted to forceUpdate them. Any suggestions on how to resol ...

Have you not heard of the greatness of Selenium before?

I've been trying to automate the process of selecting my shoe size, adding it to the cart, and checking out whenever I visit a sneaker page like FootLocker or FootAction. However, each time I attempt to run the script, I encounter the following error: ...

Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it : <div class="map"> <div class="map-page" tabindex="0" @keyup.arrow-keys="show" ref="mapPage"> <template v-for="mapRow in mapMatrix"> < ...

The state in useState is failing to update correctly following selections made within the dropdown menus

I am currently facing an issue with my dropdown disabling function, which is not enabling the dropdown properly. I suspect that this is due to asynchronous problems stemming from the use of useState. const [homeSelect, setHomeSelect] = useState('Home& ...

verifying the presence of a specific key within a dictionary in Python

Check out the javascript code snippet: const isValid = function (area, row, col, num) { if (area[num] || row[num] || col[num]) { return false; } else { return true; } }; I attempted to convert this into python but encountered some difficulti ...

Attempting to activate cookies, however receiving a message indicating that cookies are not enabled

When trying to log in to a page using request in my node.js server, I set 'jar' to true like this: var request = require('request'); request = request.defaults({jar: true}); After that, I make a post request with the login details: r ...

Implementing Facebook Javascript SDK to enable login and trigger re-authentication using React Web and Typescript within a component

As a newcomer to stack overflow, I welcome any suggestions on how I can improve my question. I'm in need of guidance concerning logging a user into facebook and requiring them to authenticate their profile or select another profile manually, rather t ...

Arrange divs on the screen in a specific formation

I am exploring ways to position specific divs in the middle of the screen to create a pearl necklace-like shape. The desired shape is as follows: 0 0 0 0 0 0 0 0 0 0 My aim is to achieve this using jQuery on a mobile ...