What is the method for incorporating locales into getStaticPaths in Next.js?

I am currently utilizing Strapi as a CMS and dealing with querying for slugs. My goal is to generate static pages using getStaticPaths and getStaticProps in Next.js.

Since I'm working with multiple locales, I have to iterate through the locales to retrieve paths for each "Announcements" obtained from my query.

The issue I am encountering displays the following error message:

Error: A required parameter (slug) was not provided as a string in getStaticPaths for /updates/announcements/[slug]

This is the code snippet for my getStaticPaths function:

export async function getStaticPaths({ locales }: any) {
  const paths = await (
    await Promise.all(
      locales.map(async (locale: any) => {
        const { data } = await client.query({
          query: gql`
            query Announcements {
              announcements(locale: "${locale}") {
                data {
                  attributes {
                    slug
                    locale
                  }
                }
              }
            }
          `,
        });
        return {
          announcements: data.announcements.data,
          locale,
        };
      })
   )
  ).reduce((acc, item) => {
    item.announcements.map((p: any) => {
      acc.push({
        params: {
          slug:
            p.attributes.slug === "/" ? false : p.attributes.slug.split("/"),
         },
         locale: p.attributes.locale,
     });
      return p;
   });
    return acc;
 }, []);

   return {
    paths,
    fallback: false,
  };
}

When I log the paths to the console, the output looks like this:

[
  { params: { slug: [Array] }, locale: 'en' },
  { params: { slug: [Array] }, locale: 'en' },
  { params: { slug: [Array] }, locale: 'en' },
  { params: { slug: [Array] }, locale: 'da' },
  { params: { slug: [Array] }, locale: 'sv' },
  { params: { slug: [Array] }, locale: 'nb' }
]

I suspect that Next.js may not accept the slug as an array, but I am unsure about the exact mistake I am making. Can someone point me in the right direction?

Answer №1

Your webpage utilizes dynamic routes called (/updates/announcements/[slug]), hence the parameter slug is necessary in paths.

According to the documentation for Next.js getStaticPaths:

The paths key defines which paths will be pre-rendered. For example, if you have a page using Dynamic Routes named pages/posts/[id].js. When you export getStaticPaths from this page and return the following for paths:

return {
 paths: [
   { params: { id: '1' }},
   {
     params: { id: '2' },
     // with i18n configured the locale for the path can be returned as well
     locale: "en",
   },
 ],
 fallback: ...
}

In this scenario, Next.js will statically generate /posts/1 and /posts/2 during next build using the page component in pages/posts/[id].js.

The slug parameter must be of type string since it's used for generating routes. As mentioned when logging paths, you were attempting to pass slug: [Array].

The issue in the code snippet provided is in this line for assigning a slug:

// ...
params: {
  slug: p.attributes.slug === "/" ? false : p.attributes.slug.split("/"), // 👈
},
// ...

This logic will assign either false (boolean) or an array of substrings based on the condition (refer to the docs for String.prototype.split()).

In this case, as stated in a comment above, simply passing the slug as a string resolves the problem.

The confusion likely arose from following a guide that uses an optional catch-all route (pages/[[...slug]]) instead of regular dynamic routes (pages/[slug]) (reference).

In conclusion, per the Next.js getStaticPaths documentation:

  • For a page named pages/posts/[postId]/[commentId], params should include postId and commentId.
  • If the page uses catch-all routes like pages/[...slug], params should consist of slug (an array). If the array is ['hello', 'world'], Next.js will pre-render the page at /hello/world.
  • When encountering an optional catch-all route, use null, [], undefined, or false to render the root-most route. For instance, by setting slug: false for pages/[[...slug]], Next.js will statically generate the page /.

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

I am using multiple useState hooks, but only one of them is functioning properly

https://i.stack.imgur.com/qMSR1.png https://i.stack.imgur.com/Sucdt.png Within this block of code, I have defined three useState variables. The first one, boola, is functioning as expected. However, the functions func and func2 are not working correctly; ...

Steps for deactivating AMD on four files and sequentially loading them using webpack

I am facing an issue where I need to disable AMD on 4 files and ensure that video.js is loaded before the other 3 files, as they are dependent on it. My attempt to achieve this in webpack.config.js was unsuccessful: const path = require('path') ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

How do I retrieve the enclosure URL in the Alexa Skill FeedHelper.js file?

I am currently working on a project to create an Alexa feed skill using a blueprint provided by Amazon. The blueprint involves calling RSS feeds from a URL, transforming them into JSON format, and saving them on Amazon S3. The code responsible for this fu ...

The loop feature in Swiper.js seems to be malfunctioning and not functioning as

I'm currently in the process of setting up a carousel using swiper.js and here is my setup: { slidesPerView: 1, slidesPerColumn: 1, initialSlide: this.initialSlide, loop: true } As expected, I'm encountering an issue where dupl ...

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Utilizing variables as identifiers in React Native programming

Trying to utilize a dynamic name for a property of an object. For instance, within the function provided below, aiming to use the value stored in the variable 'catagoryId' to access the corresponding child element and assign it to the variable c ...

Encountering a NextJS pre-render issue while generating the sitemap.xml

While developing my markdown-based blog, everything functioned smoothly in the developer environment. However, when I attempted to build the project using the command npm run build, I encountered an error related to pre-rendering failure. Error occurred pr ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...

Optimal strategies for initializing Knockout JS models from backend code

Upon taking over a website that utilizes knockout js and asp.net, I noticed some performance issues during the initial page load. After investigating, I found that there are approximately 20 models on the site, each making an ajax call to retrieve data fro ...

Adding an image within the body of text in a Django model, where both the text and image coexist

I am currently seeking a method to seamlessly insert an image within the text of my Django-powered blog. My goal is to achieve a layout similar to the one showcased in this example: https://i.stack.imgur.com/cFKgG.png The desired layout consists of two c ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

What is the best way to deploy Material UI icons on Vercel?

I am currently in the process of deploying my website on Vercel. Everything is functioning properly on my localhost3000, however, when I attempt to deploy it on Vercel, I continuously receive the following error message: "Module not found: Can't resol ...

Can this JSON object be created? If so, what is the process to do so?

Is it possible to create a JSON array with integers like the examples below? "data" : [ "1000": "1000", "1200": "1200", "1400": "1400", "1600": "1600", "1800": "1800", ] or "data" : [ 1000: 1000, 1 ...

Issue encountered when attempting to locate the file path within the getStaticProps function of an internal page in Next Js

I'm currently implementing a multi-language feature on my Next JS app. Below is the folder structure of my project. https://i.stack.imgur.com/5tD2G.png On the Home page (index page), I successfully retrieved the locales module using getStaticProps: ...

What is the best way to send an API request from a React frontend to my Next.js backend running on localhost?

I have currently developed a create react app and I am interested in creating a next.js backend for it. I have set up an API route on the server-side which will fetch data from another API and generate a response accordingly. I do not want to fully migrate ...

Handling Removal of Selected Option in React Material-UI Autocomplete Single Selection

I am currently using material UI autocomplete to create a single-select dropdown. However, I have encountered an issue wherein the onChange event does not get triggered when I click the close button on the right side of the input. This prevents my state fr ...

How can I access the rendered HTML element from a component in Vue 3?

This particular component is known as LayerComponent (placeholder). <script> export default { data() { return { count: 0 } } } </script> <template> <button @click="count++">You have clicked me {{ count ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...