Nextjs 404 error on reload/ refresh action

Viewed 11632

I'm using Nextjs for a front-end application and dotnet core 3.1 for the Web API. There are some pages that are static and other that are dynamic I followed the official documentation to achieve this. On development mode (local machine) everything works fine. Both static and dynamic routes are working properly and fetching data from the dontnet core Web API.

However, when publishing the Nextjs app following this steps:

  1. yarn build
  2. yarn export
  3. An out folder is generated at the root of the project
  4. The content of that folder is uploaded to the server

After, the deployed files are uploaded and when loging to the app, it redirects to the main page (until here is working OK), but as soon as I click on the reload page botton (Chrome) I am gettint the 404 error.

enter image description here

Looking at the console in the developer tools I got this: enter image description here

I found this Stackoverflow link with same issue but there the answer is to use Express for server routing. In my case I am using dotnet core Web API for server requests. So, not sure how to do that.

Is there a way to fix this from the client side? Might be a configuration is missing?

The only thing I noticed while doing the export was a message saying: No "exportPathMap" found. Not sure if that would the the reason.

enter image description here

2 Answers

I had got similar issue in react when all of my pages after building and exporting had ".html" extensions. I solved it by the following code in next.config.js file.

next.config.js

module.exports = {
  exportTrailingSlash: true,
}

Note: Do not work with the above code while in development. Use it just before building the project.

You can find the documentation link here: https://nextjs.org/docs/api-reference/next.config.js/exportPathMap#adding-a-trailing-slash.



UPDATE

The above code was for next.js v9.3.4 which I was using at that time. For newer versions below code should be used according to docs.

next.config.js

module.exports = {
  trailingSlash: true,
}
Related