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

What is causing this issue with the ajax call not functioning correctly?

$(document).ready(function(){ $('.clickthetext').click(function(){ $.post("submit.php", $("#formbox").serialize(), function(response) { $('#content').html(response); }); return false; }); ...

What is the process for transforming a nested dictionary in JSON into a nested array in AngularJS?

I am looking to create a form that can extract field values from existing JSON data. The JSON I have is nested with dictionary structures, but I would like to convert them into arrays. Is there a way to write a recursive function that can retrieve the key ...

Accordion feature that loads JSON data dynamically with AJAX

I am facing a challenge with my HTML structure and corresponding CSS styling. The HTML code includes an accordion container with multiple sections that can be expanded or collapsed. <div class="accordion-container"> <ul class="accordion"> ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

Tips on updating the $authProvider.loginUrl for Satellizer from an Angular controller

Consider this hypothetical situation: A user attempts to access a /settings page without being logged in. The Settings controller detects based on $auth.isAuthenticated() != true that the user is not logged in, and directs them to the /login page. The us ...

Tips for troubleshooting ImageArray loading issues in AngularJS

Having some trouble learning Angular and getting stuck with this Image array. Can someone please help me understand what's wrong with my code and how to fix it? FilterAndImages.html <!DOCTYPE html> <html ng-app="store"> <head> < ...

Improving the functionality of dynamically updating server-side rendered props

I have posts with comments and I would like to create a post view that displays all the comments for that post. In my implementation, the getServerSideProps function passes the entire post (including comments) to the page. My goal is to dynamically update ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

tips for storing user input into an array

I am currently developing a calculator that uses Json data. The goal is to retrieve the Grid Code associated with a specific longitude and latitude input. However, I am encountering an issue where the result returned is 0, indicating that the value of the ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

The Next.js API has a mysterious parameter that remains undefined

I currently have a component implemented import React, { useEffect } from "react"; import styles from "../styles/success.module.css"; import { useRouter } from "next/router"; import axios from "axios"; const Success ...

I am not encountering any errors; however, upon entering the room, my bot fails to initiate creation of a new channel

const Discord = require("discord.js") const TOKEN = "I forgot to include my token here" const { Client, GatewayIntentBits } = require('discord.js'); const { MemberFetchNonceLength } = require("discord.js/src/errors/Erro ...

tips for utilizing namespaced getter filtering within a Vuex module in vueJs

In my custom module named ShopItemCategory, I have a Getter getters: { shopItemsCategories: state => state.ShopItemsCategories.data, }, Inside the component, there is a computed function I defined computed: { shopItemsCategories ...

Why isn't my Next.js middleware working properly with TypeScript?

My issue arises from the fact that, despite following the documentation, the middleware in Next.js is not functioning as I anticipated. I experimented with what I thought was the simplest middleware possible. I expected that when navigating to /, a conso ...

Encountered an npm compilation error - Unable to locate module: bootstrap-theme.css

I recently updated all the dependencies in my JavaScript program without making any changes to my components or index.js file. However, when I run npm run build I encounter an error with index.js related to bootstrap-theme.css: Failed to compile. Modul ...

tag of data in jquery

Here is how my setup looks: <div onclick="EditCalendarEvent('@_schedulerEvent.SchedulerID','@_schedulerEvent.SchedulerItemID', event)" class="ScheduleEvent_Draggable ScheduleEvent" data-schedulerID="@_schedul ...

Resetting text in an input field using CSS

Here is the fiddle link for reference: http://jsfiddle.net/a765q/1/. I noticed that when I click the reset button, the text color changes to grey. Any ideas on how to fix this? ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

Creating smooth animations in JavaScript without relying on external libraries such as jQuery

Is there a way in JavaScript to make a <div> slide in from the right when hovered over, without relying on jQuery or other libraries? I'm looking for a modern browser-friendly solution. const div = document.querySelector('.fro ...

The functionality of res.send is not working correctly

Attempting to send a response from my express application to the front-end in order to display an alert. Here is what I have attempted in my app: if (info.messageId) { res.redirect('back'); res.send({ success: true }); } ...