NextJs getStaticPaths function is failing to render the correct page, resulting in a 404 error message being displayed

Hey there, I'm in a bit of a pickle as I've never used 'getStaticPaths' before and it's crucial for my current project!

I followed the example code from NextJs's documentation on 'getStaticPaths', but when I try to access a supposed route like 'http://localhost:3000/1', it shows a 404 not found error. My custom API is powered by Strapi, and testing it in Postman returns the GET request with a JSON response below.

I'm really confused as to why this isn't functioning as expected. Any guidance or assistance would be highly appreciated!

Also, is there a way to change the route to '/Math' instead of '/1'?

Thank you in advance for your help!


        "id": 1,
        "name": "Math",
        "published_at": "2021-10-08T04:32:51.871Z",
        "created_at": "2021-10-08T04:32:50.777Z",
        "updated_at": "2021-10-08T04:32:51.883Z",
        "papers": [
            {
                "id": 1,
                "name": "Maths Standard 2020 Past Papers 1",
                "description": "# 2020 Maths Standard Past Papers 1\n\nOriginal Source: [Source](https://educationstandards.nsw.edu.au/wps/portal/nesa/resource-finder/hsc-exam-papers/2020/mathematics-standard-2020-hsc-exam-pack)",
                "pdf_gcs_link": "https://storage.cloud.google.com/matsites/2020-hsc-mathematics-standard-1.pdf",
                "published_at": "2021-10-08T04:39:01.111Z",
                "created_at": "2021-10-08T04:38:49.013Z",
                "updated_at": "2021-10-08T05:21:32.293Z",
                "pdf": [
                    {
                        "id": 1,
                        "name": "2020-hsc-mathematics-standard-1(1).pdf",
                        "alternativeText": "",
                        "caption": "",
                        "width": null,
                        "height": null,
                        "formats": null,
                        "hash": "2020_hsc_mathematics_standard_1_1_1e764b3f71",
                        "ext": ".pdf",
                        "mime": "application/pdf",
                        "size": 612.42,
                        "url": "/uploads/2020_hsc_mathematics_standard_1_1_1e764b3f71.pdf",
                        "previewUrl": null,
                        "provider": "local",
                        "provider_metadata": null,
                        "created_at": "2021-10-08T04:37:35.185Z",
                        "updated_at": "2021-10-08T04:37:35.192Z"
                    }
                ]
            }
        ]
    },
    {
        "id": 2,
        "name": "English",
        "published_at": "2021-10-08T04:32:59.966Z",
        "created_at": "2021-10-08T04:32:58.804Z",
        "updated_at": "2021-10-08T04:32:59.974Z",
        "papers": []
    }
]
// pages/posts/[id].js

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

    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()
  
    // Pass post data to the page via props
    return { props: { categories } }
  }
  
  export default Category
  

// categories response
Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'http://localhost:1337/Categories',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

Answer №1

There appears to be an error in the fetch function within the getStaticProps. The issue lies with the missing forward slash after Categories:

const res = await fetch(`http://localhost:1337/Categories/${params.id}`)

To resolve this, you can update the route by substituting category.id with category.name in the getStaticPaths function:

params: { id: category.name},

This adjustment will require modifications to both the fetch call in getStaticProps and the relevant api endpoint. Alternatively, consider implementing next.js rewrites for a more efficient solution.

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

Customizing a tinyMCE button with a unique icon

I'm attempting to insert a Font-Awsome icon into a button that I included in tinyMCE using the following code: ed.addButton('youtube', { title: 'Add Video' , icon: 'icon-youtube', onclick: function () { ...

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Tips for organizing and sorting date data in a JSON datatable

I am working with two date input fields: <form id="refresh" method="post" action="income.php"> <input type="text" id="dari" name="dari" /> <input type="text" id="sampai" name="sampai" /> <button type="submit">Refresh</b ...

I am encountering an issue stating "indexRouter has not been defined"

Encountering an error "indexRouter is not defined" while attempting to run the code below. Despite attempts to remove the line, additional errors persist. Can anyone clarify the rationale behind using the common variable router for both index.js and user.j ...

`The value of an element within an array changes automatically`

In my current setup, I have a traditional array where each element represents an HTML element. The issue arises when I manipulate these elements within the array; any changes made to the HTML element also reflect in the array automatically. However, I pref ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

Guide on ensuring the client waits for authorization state to load before requesting data

Recently, I discovered the useAuth and useRequireAuth hooks which can be found at . These hooks are extremely valuable for client-side authentication. However, I'm curious about the best approach to wait for authentication data before fetching additio ...

javascript functionality may be affected in Internet Explorer and Firefox following the upgrade to jquery version 1.8.3

After upgrading to jquery 1.8.3 from jquery 1.7 (where everything was functioning properly in all browsers), I added a javascript plugin that specifically requires jquery 1.8.2 or 1.8.3 Unfortunately, the image resizing functionality of this javascript is ...

The functionality of Ajax autocomplete with jQuery does not function properly when the text field contains existing text

Currently, I am utilizing Ajax autocomplete for jquery in my project. Below is the HTML code snippet I have implemented: <input type="text" name="autocomplete" id="globalBCCAutoComplete"> Furthermore, here is the JS code utilized for the autocomple ...

json How to retrieve the first index value in jQuery

As part of my Ajax loop, I am successfully generating JSON and iterating through the results. My goal is to extract only the first index value of JSON which is name. In jQuery, I have the following code: PHP $jsonRows[] = array( "name" => ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

When directly called from index.js, Next.js getStaticProps and getInitialProps return undefined for a component

I've been following this tutorial: https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops, but I decided to create a new component instead of adding the code directly to the index.js file. Although the tutorial's method works fin ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Scrolling to the latest message in Vuejs when a new message is received

I am currently working on a chat application, but I am facing an issue with scrolling to the bottom when new messages are received. I have attempted both methods: document.getElementById('msg_history').scrollTop = document.getElementById('m ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

VueJS does not refresh other components in the application

I am working with two components. Let's start with Component 1: <template> <div> <div class="form-group"> <label for="group">Category</label> <select name="category" v-model="category" @change="setCategory(ca ...

AngularJS Element Connections

I have the following component: (function () { "use strict"; angular.module("application_module") .component('tab', { controller: 'TabCtrl', templateUrl: 'app/component/application/app-heade ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

What is the best way to format MarkDown content within a nextJs environment?

Markdown-it is successfully converting markdown to html in my Nextjs project. However, I am facing a styling issue with specific elements such as h2, h3, ul, and li. Here's the code snippet: <h1 className="text-3xl mb-3 leading-snug d ...