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

JavaScript: A guide to solving systems of equations

I'm attempting to perform algebraic operations in JavaScript using certain conditions and known variables. However, I lack proficiency in mathematics as well as JavaScript to comprehend how to articulate it. Here are the conditions: var w1 = h1/1.98 ...

Guidelines for showcasing a map on my website with the option for users to select a specific country

Is there a method to showcase a global map on my site and let the user select a country to receive relevant information? I am aware of embedding Google Maps, however, it includes unnecessary controls like zooming which I prefer not to inconvenience the us ...

Step-by-step guide to launching a new window or tab without automatically bringing it into focus

Is it possible to use JavaScript to open a URL in a new tab without giving that tab focus on a click event? ...

Implementing Passport authentication for Steam, transitioning from Express to NestJS

I have embarked on the task of transitioning an express project to nestjs. How can I achieve the same functionality in Nestjs as shown in the working code snippet from Express below? (The code simply redirects to the Steam sign-in page) /* eslint-disable s ...

Endless jasmine timeout

This question is a continuation of a discussion on the Remove timeout for single jasmine spec GitHub issue. Query: Can a single test be configured to never time out? The Issue: While it's possible to set a global timeout value using DEFAULT_TIMEOU ...

What is the best way to retrieve data from an entity with Prisma where the number of its children exceeds a certain threshold?

I am working on a project where I have an entity called Author that can have multiple Books associated with it. My goal is to retrieve all Authors who have more than 5 books in my database. The application is built using Prisma in conjunction with Next.js ...

How can I create a dashed border for a pie chart using highcharts?

Is there a way to change the default solid border of a pie highchart to dashed? This modification is only necessary for pies without data or with negative data values. Perhaps it's possible to redraw the SVG of the border, like in this example: https: ...

Combine filter browsing with pagination functionality

I came across a pagination and filter search online that both function well independently. However, I am looking to merge them together. My goal is to have the pagination display as << [1][2] >> upon page load, and then adjust to <<[1]> ...

Arranging items into an array?

I have a query. Let me start by posting the HTML code, even though I know using tables for design is not recommended. However, in this case, it's only for educational purposes. <table id="placeholder"> <tr> <td><img src="img/ ...

Guide on effectively managing props within a single component in React Navigation

When attempting to navigate from my App component to the GamePlay component, I encountered an issue. Here is a snippet of my App.js: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; imp ...

Submitting a PDF document to the server with PHP Laravel through AJAX

Struggling to send a PDF file via AJAX to my server for handling by a PHP script in a Laravel project. The file doesn't seem to be making it to the server. Despite receiving a 200 response in the network, the server is returning 'file not presen ...

Converting JSON to JS in Django results in an error: SyntaxError indicating a missing colon after the property

I'm trying to figure out how to incorporate a JSON file into a script. I've been unsuccessful in loading it from the filesystem, so I created a view that serves the JSON data directly to the page like this: def graph(request, d): ...

Insert JavaScript into this HTML document

I am looking to integrate the "TimeCircles JavaScript library into my project, but I am facing some challenges in doing it correctly. I plan to include the necessary files at the following location: /js/count-down/timecircles.css and /js/count-down/timecir ...

Ways to determine the presence of a value in an array using AngularJs

I'm currently working on looping through an array to verify the existence of email, phone, and alternate phone in a database. My challenge lies in finding a suitable function or workaround in AngularJS that allows me to iterate through the array with ...

Strange rendering in CSS JQuery Datatable

I am encountering an issue with a DataTable from datatables.net. Each row can be selected by clicking on a checkbox, which triggers a click event. In response to the event, I add or remove a CSS class to change the appearance of the selected rows. $(".cbD ...

Refresh a TextBox using an Ajax Response

Is there a way to dynamically update a textbox with the response from an ajax call? I've managed to get the response and assign it to the textbox using: document.getElementById("testPad").value = xmlHttpRequest.responseText; The issue is that the en ...

Turning a string retrieved from the element's data attribute into a JSON format

I am running into an issue with the code snippet below. It seems that $.parseJSON() is having trouble with single and double quotes. I'm stuck on finding a solution to this problem. Any help would be greatly appreciated! <div data-x='{"a":"1" ...

Differences seen in display when using Internet Explorer's prependTo feature

Here is some code that I am working with:- <ul id="list1"> <li class="a">item 1</li> <li class="a">item 2</li> <li class="b">item 3</li> <li class="b">item 4</li> </ul> Additiona ...

Issue: Configuration Error - CKEditor5 cannot be loaded for extension in Vuejs

Hey everyone, I'm currently facing an issue. I'm trying to customize a build and everything works fine in the cloned ckeditor along with the sample.html file. However, when attempting to implement the customized build in Vue 2, I encounter an err ...

Having difficulty uploading a file using a formGroup

Currently, I am using Angular to create a registration form that includes information such as name, email, password, and avatar. For the backend, I am utilizing NodeJS and MongoDB to store this information. I have successfully written the registration API ...