Next js 404 on refresh

Next.js 404 on Refresh

When developing a Next.js application, you may encounter a situation where navigating directly to a nested route or refreshing a page results in a 404 error. This happens because Next.js by default handles the routing on the client-side using JavaScript, so when you refresh a page or directly access a nested route, the server doesn’t know how to handle it and returns a 404 status code.

To fix this issue, you can configure Next.js to use server-side rendering (SSR) for all pages, including nested routes. SSR essentially means that the server will render the complete HTML content for each page before sending it to the client, ensuring that the desired route is correctly handled even when accessed directly.

Step 1: Install and Set Up Server Middleware

The first step is to install the required server middleware to handle SSR. One popular choice is to use Express.js. Assuming you already have a Next.js project set up:

    
      $ npm install express
    
  

Next, create a custom server file in the root directory of your project (e.g., server.js) with the following content:

    
      const express = require('express');
      const next = require('next');
      
      const dev = process.env.NODE_ENV !== 'production';
      const app = next({ dev });
      const handle = app.getRequestHandler();
      
      app.prepare()
        .then(() => {
          const server = express();
          
          server.get('*', (req, res) => {
            return handle(req, res);
          });
          
          server.listen(3000, (err) => {
            if (err) throw err;
            console.log('> Ready on http://localhost:3000');
          });
        })
        .catch((ex) => {
          console.error(ex.stack);
          process.exit(1);
        });
    
  

This sets up an Express server that handles all incoming requests (including nested routes) and forwards them to Next.js for rendering. Note that in this example, the server is set to listen on port 3000. You can change it according to your needs.

Step 2: Update package.json

The next step is to update your package.json to use the custom server file created in the previous step. Modify the “scripts” section as follows:

    
      "scripts": {
        "dev": "node server.js",
        "build": "next build",
        "start": "NODE_ENV=production node server.js"
      }
    
  

Now, when you run “npm run dev” or “npm run start” to start the development or production server respectively, it will execute the custom server file instead of the default Next.js server.

Step 3: Test and Verify

Finally, restart your development or production server and navigate to your application. Now, refreshing a page or directly accessing a nested route should work correctly without resulting in a 404 error.

By setting up server-side rendering for your Next.js application, you ensure that the server handles all routing scenarios correctly, improving the overall user experience and search engine optimization (SEO) of your application.

Note: If you’re deploying your Next.js application to platforms like Vercel or Netlify, you don’t need to set up a custom server, as they handle server-side rendering (SSR) by default.

I hope this explanation helps! Let me know if you have any further questions.

Similar post

Leave a comment