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

Is there a way to update the dictionary in the context processor without having to reload the page?

I have implemented a custom context processor that returns the value of "unread_messages_count". However, when I try to update this value on the template using the following JavaScript: var update_message_count = setInterval(function(){ ...

What is the best method to position images in the same way as seen in the screenshot

Any tips on aligning images shown in the screenshot? Please note that the images will be from the backend. https://i.stack.imgur.com/LnYLM.jpg I experimented with code to position images using top, right, left, and bottom properties, but it becomes cumb ...

Storing information in a MongoDB database using Node.js

Context: Looking to insert data into a MongoDB database using Node.js Problem Statement: Attempting to insert data into the MongoDB database but encountering an error. Unable to locate the issue. Present Output: Reference Error Attach Code: filter.js ...

NextJs API endpoint that returns a response object without the keys 'message' or 'body' included

In my NextJs application, Users are able to input data into form fields and submit the Formik Form. The API route handles form submission for calculations, which must be done on the server side in this scenario. Everything is working smoothly except for ...

React Native has encountered an issue with an undefined object, resulting in an error

I have a JSON file with the following structure: { "main": { "first": { "id": "123", "name": "abc" }, "second": { "id": "321", "name": "bca" } } } Before making an AP ...

The ng-repeat function in AngularJs does not display the data despite receiving a successful 200 response

As part of my academic assignment, I am exploring Angularjs for the first time to display data on a webpage. Despite receiving a successful http response code 200 in the Chrome console indicating that the data is retrieved, I am facing issues with displayi ...

Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked. However, we are facing issues where clicking on the order button doesn't register in the applicat ...

Using API calls to update component state in React-Redux

I am currently working on setting up a React application where clicking on a map marker in one component triggers the re-rendering of another component on the page. This new component should display data retrieved from a database and update the URL accordi ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

Utilize resources from webpack's bundled npm package assets

I've been racking my brain over this issue for quite some time now, and I'm starting to wonder if it's even achievable. Any assistance on this matter would be greatly appreciated! The npm dilemma I have an npm package that serves as a coll ...

Issue with Vue2: encountering an error with the view-router component when attempting to utilize the <router-view> tag

Currently delving into Vue2 for the first time and facing hurdles with routes. Ever since I inserted <router-view></router-view> in index.html, an exception has been popping up: [Vue warn]: Failed to mount component: template or render functi ...

Tips for navigating through complex JSON structures with JavaScript or JQuery

I'm currently navigating the complexities of parsing a multi-level JSON array as a newcomer to JSON. I am seeking solutions using either JavaScript or jQuery. My goal is to extract the application id, application description, and Product description f ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

SignalR error: A type conversion issue has occurred where it is not possible to directly convert a task returning an object to a string

I'm encountering an issue with my C# hub class where the JavaScript code is returning a System.Threading.Tasks.Task instead of a string. I need help modifying the JavaScript method to return an actual string. Below is the hub class: public String ge ...

Is it advisable to supply the top-tier image quality for the next.js Image component?

Is it possible that providing 100% JPGs or 2x sized PNGs to the Image component could impact website performance and SEO in the long run? I've noticed that when supplying optimized images with reduced quality and size, the actual image displayed on th ...

Navigating to a different state key within a state object in React - a simple guide

Trying to dive into React, I encountered an issue. My goal is to create my own example from a tutorial. import React, { Component } from 'react'; class MyComponent extends Component { state = { persons: [], firstPersons: 5, variab ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Javascript - Relocating a file to a different folder in a node.js environment

I am looking to duplicate a file and relocate it within the directory structure. Current file location: Test.zip -> Account/Images/ -account.png -icon.png -flag.png . ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

Difficulty maintaining list formatting in AngularJS and Bootstrap due to ng-repeat functionality

I'm currently working on a project where I need to display content from an array using ng-repeat in Angular. The content is originally in JSON format, but it has been stringified before being added to the array. The problem I am facing is that this c ...