FIXED: Next js pages with trailing slash


Posted 5 months ago by Ryan Dhungel

Category: Next JS Web Development

Viewed 1270 times

Estimated read time: 2 minutes

Are you getting 404 error page when your next js pages(url) are accessed with trailing(ending) slash at the end? I came across this issue when I wanted to move my existing site to a new site that was built using next js.
 
If your pages are alerady indexed by google with ending slash like so domain.com/blog/my-blog/
Then this page will return 404 error: domain.com/blog/my-blog
 
This is a disaster for exising SEO pages but luckily with a bit of a regular expression we can fix this issue.
 
    • Create a file called server.js in the root of your next js project.

      // server.js
      const express = require("express");
      const next = require("next");
      const bodyParser = require("body-parser");
      
      const dev = process.env.NODE_ENV !== "production";
      const app = next({ dev });
      const handle = app.getRequestHandler();
      
      app.prepare().then(() => {
        const server = express();
        server.use(bodyParser.json());
      
        server.get("*", (req, res) => {
          req.url = req.url.replace(/\/$/, "");
          if (req.url == "") {
            req.url = "/";
          }
          return handle(req, res);
        });
      
        server.listen(3000, err => {
          if (err) throw err;
          console.log("> Read on http://localhost:3000");
        });
      });
       
    • Modify your start script in package.json so your app runs correctly in both dev and production mode.
       
      // package.json
       "scripts": {
          "dev": "NODE_ENV=development node server.js",
          "now-build": "next build",
          "build": "next build",
          "start": "NODE_ENV=production node server.js",
        },
 
  • In development you can run npm run dev
  • In production you can run pm2 start npm -- start