Encountering an error with NextJs & Strapi when utilizing the getStaticPaths functionality

Currently, my project involves using Strapi to develop a custom API and NextJs for the frontend. I am experimenting with utilizing getStaticPaths to generate pages based on different categories. In Strapi, I have set up a collection for categories that is linked to my papers collection. Testing the API routes with Postman has been successful; however, NextJs throws an error when trying to access the getStaticPaths route, which should be

http://localhost:3000/categories/1
. Instead, I encounter the following error message:
Error: A required parameter (category) was not provided as a string in getStaticPaths for /categories/[category]
. I'm puzzled because I converted it to a string as recommended, so why isn't the error resolved? Keep in mind, I'm not an expert in NextJs.

If I manually enter the route in either Postman or my browser, it functions correctly, displaying the accurate JSON output. Yet, the console in Strapi confirms receiving the request, but this confirmation doesn't appear in the console when Next attempts to load the page, presumably because it's not reaching that stage.

How can I resolve the aforementioned error? I've spent days on this issue, and it's becoming quite frustrating!

// pages/categories/[category].js

function Category({ categories }) {
 return (
    <>
    <h1>{categories.name}</h1>
    <h2>{categories.papers.name}</h2>
    </>
   )
  }
  
  export async function getStaticPaths() {
    const res = await fetch('http://localhost:1337/Categories')
    const Categories = await res.json()
    await console.log(Categories);
  
    const paths = Categories.map((category) => ({
      params: { id: category.id.toString() },
    }))

    return { paths, fallback: false }
  }
  

  export async function getStaticProps({ params }) {
    // params contains the post `id`.
    // If the route is like /posts/1, then params.id is 1
    const res = await fetch(`http://localhost:1337/Categories/${params.id}`)
    const categories = await res.json()
    console.log(categories)
  
    // Pass post data to the page via props
    return { props: { categories } }
  }
  
  export default Category

The expected response for

http://localhost:1337/Categories/**${params.id}**
- which would ideally be 1, making the URL
http://localhost:1337/Categories/1

{
    "id": 2,
    "name": "English",
    "published_at": "2021-10-08T10:12:08.041Z",
    "created_at": "2021-10-08T10:12:04.011Z",
    "updated_at": "2021-10-08T10:12:08.061Z",
    "papers": [
        {
            "id": 1,
            "name": "2020 English Studies (Testing)",
            "description": "# Testing",
            "PDF_link": "/uploads/2020_hsc_english_studies_98eabce6e7.pdf",
            "published_at": "2021-10-08T10:14:55.816Z",
            "created_at": "2021-10-08T10:12:48.714Z",
            "updated_at": "2021-10-08T10:14:55.835Z",
            "Media_Upload": [
                {
                    "id": 1,
                    "name": "2020-hsc-english-studies.pdf",
                    "alternativeText": "",
                    "caption": "",
                    "width": null,
                    "height": null,
                    "formats": null,
                    "hash": "2020_hsc_english_studies_98eabce6e7",
                    "ext": ".pdf",
                    "mime": "application/pdf",
                    "size": 4959.79,
                    "url": "/uploads/2020_hsc_english_studies_98eabce6e7.pdf",
                    "previewUrl": null,
                    "provider": "local",
                    "provider_metadata": null,
                    "created_at": "2021-10-08T10:14:32.827Z",
                    "updated_at": "2021-10-08T10:14:32.847Z"
                }
            ]
        }
    ]
}

Answer №1

Ensure that the keys in params match your dynamic route name. For example, if your route is named /categories/[category], you should pass the key as category instead of id.

    const paths = Categories.map((category) => ({
      params: { category: category.id.toString() },
    }))

In the getStaticProps function, make sure to also retrieve the value of category from params.

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

Caution: Potential Unresolved Promise Rejection Detected (ID: 21) - Error: Undefined is not a valid object when trying to evaluate 'res.json'

ERROR Getting an Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json'). Any suggestions on fixing this issue in my code? I've checked the logs for user and loggeduserobj, and they seem to be cor ...

Setting bootstrap datetimepicker values dynamically from a variable

I'm trying to utilize the inline bootstrap datetimepicker from At the moment, it opens in a popup window after the user selects a date/time from a table on another page. My goal is to pass the date/time from that page into datetimepicker and have it ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

The method defined in user.model.js cannot be utilized in mongoose and node

When developing an app with node and mongoose, I encountered a peculiar issue while testing. Below is my auth.index.js file for user login. auth.index.js: var express = require('express'); var mongoose = require('mongoose'); var passp ...

Issue with JavaScript Date.parse function not functioning as expected

I have implemented a date validation method in my application to check if a given date is valid or not. myApp.isValidDate = function(date) { var timestamp; timestamp = Date.parse(date); if (isNaN(timestamp) === false) { return true; } return ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Guide to triggering an action in next.js using getStaticProps

I'm a beginner in NextJs and I'm looking to have my component load after an API call is resolved. Additionally, I'd like to save the response from this API call in the redux store. Below is the code snippet for my component: const BlogPage ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

HTML string decoded incorrectly in CodeIgniter due to encoding error

When I send data that includes an HTML string along with other information from JavaScript to the PHP (Codeigniter) server using AJAX and JSON, I notice that the style information within the HTML string is missing once it reaches the server. Everything els ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...

Interactive AJAX div click functionality

For this code to work, the user needs to first click the like button and then continue to proceed. However, I am having trouble getting the div event to function properly. The like button is located within a div called postos. When something is clicked wit ...

Using Sequelize and Express API for verification in the controller is an essential component of building

I'm currently working on building the API for my web app, utilizing Sequelize and Express. I have set up models with Sequelize and am in the process of developing controllers and endpoints. My main query is: Should I perform data validation checks be ...

Leveraging nodemailer and handlebars for personalized email templates

I'm encountering an issue and struggling to pinpoint what exactly is causing it. Whenever I execute my code, the following error message pops up: [Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtes ...

Using ASP.NET MVC with JQuery to find the closest HiddenFor value

My current table structure is as follows: <table class="table table-bordered"> @for (var i = 0; i < Model.Count; i++) { <tr> <td width="25px"> @if (!Model[i].Letter.Equ ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

Parsing an Object in Java

I have a JavaScript object that I am sending back to Java using AJAX: var jsonData = { "testJson" : "abc", "userId" : "123" }; After printing the map, it appears as follows: key: jsondata value:[object Object] What is the correct ...