0

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?

2
  • 1
    Hi Bardhava Welcome to StackOverflow. Please add all the relevant code and you can also check this guide on How to ask Good Questions
    – Alpha
    Commented Jul 26, 2023 at 5:03
  • Please provide enough code so others can better understand or reproduce the problem.
    – Community Bot
    Commented Jul 27, 2023 at 2:02

2 Answers 2

1
 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>`
        )
      );
    } 
  });
});
0

If you are using React Router to work with client-side routing, you can also try using its StaticRouter on the server side. The StaticRouter can directly set the status code for the response based on the route match.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.