Search code examples
reactjsexpressreact-routerreact-router-dom

How to handle dynamically 404 Not Found page and status code 404 using react and express?


when hit the url It redirect to custom 404 not found page If doesn't match any of the defined routes but status code is still show 200. How can I handle status code also dynamically in react application.

How to handle with server-side rendering tools that the status code for this page should be 404 when pre-rendering the React application?

how send an actual 404 status code on not found pages?


Solution

  •  app.get("/", (req, res) => {
       
      let matchedPath = null;
      // pathsToMatch is routing of client-side routes
      for (const path of pathsToMatch) {
        const match = matchPath( { path, exact: true }, req.url);
        if (match) {
          matchedPath = path;
          break;
        }
      }
    
      
      if (!matchedPath) {
        console.log("No matching path found.");
        res.status(404)
      }
    
      fs.readFile(path.resolve("./build/index.html"), "utf8", (err, data) => {
        // console.log("inside fs");
        if (err) {
          console.log("inside fs error");
          console.error(err);
          return res.status(500).send("An error occurred");
        }
    
        if (typeof window === "undefined") {
          return res.send(
            data.replace(
              `<div id="root"></div>`,
              `<div id="root">${ReactDOMServer.renderToString()}</div>`
            )
          );
        } 
      });
    });