404 page is not showing in nextjs after export

Viewed 2207

I've added a custom 404.js file in /pages directory and it's working fine locally but when I run next export and put all files from out directory to public_html directory in cpanel, everythings is working fine but when I enter wrong path it should go to 404 page instead my web takes me to home page with same link in address bar. For Example: I don't have /about page when I try to go to /about page, my website should show me to 404 page instead it showing me home page (index.html) with /about in address bar.

next.config.js file

module.exports = {
  exportPathMap: async function (
    defaultPathMap,
    { dev, dir, outDir, distDir, buildId }
  ) {
    return {
      "/": { page: "/" },
      "/faq": { page: "/faq" },
      "/how-it-works": { page: "/how-it-works" },
      "/patient-onboarding": { page: "/patient-onboarding" },
      "/privacy-policy": { page: "/privacy-policy" },
      "/terms-of-use": { page: "/terms-of-use" },
      "/searched-pharmacy": { page: "/searched-pharmacy" },
      "/new-customer": { page: "/new-customer" },
      "/404": { page: "/404" }
    }
  },
  trailingSlash: true,
}

using "next": "^10.0.6",

server.js file

const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";

const sitemapOptions = {
  root: __dirname + "/public/",
  headers: {
    "Content-Type": "text/xml;charset=UTF-8",
  },
};

// Create the Express-Next App
const app = next({ dev });
const handle = app.getRequestHandler();
//Start the app
app
  .prepare()
  //Start Express server and serve the
  .then(() => {
    const server = express();
    // serve sitemap
    server.get("/sitemap.xml", (req, res) =>
      res.status(200).sendFile("sitemap.xml", sitemapOptions)
    );

    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);
  });

on local showing 404 page

Same path after deployment

1 Answers

At last! I found the solution for my problem. Thanks to this document

There is no issue in my NextJS configuration the issue was my .htaccess file. I've changed .htaccess file and 404 page is now working with HTTP status code 404.

I've just followed these 2 simple steps!

  1. Added 404.html file at root_level
  2. Added this line in .htaccess file ErrorDocument 404 /404.html

Note: Both .haccess and 404.html files are at root_level

Related