Reputation: 31365
I have a single page app in which all the routing is done on the client, using react-router-dom
.
My app allows a set of exact match routes.
For any route out of that set, it will be considered invalid and the client code will redirect you to the /404-page
route.
So I need to do the same when I'm rendering on the server.
This is the flow:
/invalid-route
react-router
will render a <Redirect to="/404-page"/>
/404-page
I guess I should set status = 404
. Because that route was not found, right?
Something like:
// YOU'VE REQUESTED SOME /invalid-route
res.status(404).redirect(ROUTES.NOT_FOUND);
But now you gonna ask my server for the /404-page
route. Which will actually render a 404 Page
/404-page
Should I use 200 Ok
? Since my /404-page
is a valid and existing URL that will actually render something?
// NOW YOU ARE REQUESTING MY /404-page
res.status(200).send( // 404 PAGE HTML );
Is this the right way of doing this?
UPDATE:
My question was assuming something wrong.
When a user asks for a /invalid-url
, you can't send a 404
and redirect at the same time.
Because the following code:
// YOU'VE REQUESTED SOME /invalid-route
res.status(404).redirect(ROUTES.NOT_FOUND);
// NOW YOU ARE REQUESTING MY /404-page
res.status(200).send( // 404 PAGE HTML );
Produced the following result:
[![enter image description here][1]][1]
The redirect was done using 302
even though I was using res.status(404).
.
This is not intended at all. Because no 404
status was emitted.
So I guess we should redirect /invalid-route
with 302
or 301
, and send the 404
for the /404-page
Something like:
// YOU'VE REQUESTED SOME /invalid-route
res.status(302).redirect(ROUTES.NOT_FOUND);
// NOW YOU ARE REQUESTING MY /404-page
res.status(404).send( // 404 PAGE HTML );
UPDATE 2:
This does not work as intended to send a 301
// THIS SENDS A 302, EVEN THOUGH SETTING 301
res.status(301).redirect(ROUTES.NOT_FOUND);
To send a 301 on a redirect, I had to do:
// THIS SYNTAX ALLOWS YOU TO CHOOSE THE STATUS CODE FOR THE REDIRECT
res.redirect(301,ROUTES.NOT_FOUND);
``´
[1]: https://i.sstatic.net/jNnfN.png
Upvotes: 1
Views: 74
Reputation: 1290
My gut says that a 404 page should always return a 404 status. If it comes with an actual page to display that 404 message, then that's fine. This is what I think is intuitive.
This is my mental picture for this request flow:
<Redirect to="/404-page"/>
-> ClientI think the confusion comes from thinking of the 404 page as an existing resource which should return 200 when requested. I prefer to think of the 404 page as less of a page and more of a 404 status code with some human redable html to render the code.
Upvotes: 1