React-router: Add a 404 and 501 page example

Created on 21 Nov 2016  路  6Comments  路  Source: ReactTraining/react-router

Add a 404 and 501 example with best practices.

I saw there are a bunch of issues and PRs that were closed without a solution about 4xx errors. For example I found #3210, #3181, #3098, #3098 (closed because it cannot be merged?).

I am using Router v2.8.1 with isomorphic/universal rendering.
The example https://github.com/wdjungst/react-project/blob/master/create-react-project/blueprint/modules/routes.js covers only the basic use case of hitting a route that does not exist.

  1. I think it is a pretty common use case to have a route with /user/:id that asynchronously load the data that can result with a user that does not exist. In this case you want to send a 404 and render a 404 page. Or maybe you want to have a specific 404 page for that route (user missing).
  2. Another use case is an unhanded error during the async code that should result in a 5xx page.
  3. Finally you may want to do a 301 or 302 redirect driven by async data (ex: the user is blocked, you may redirect to /user/blocked)

Most helpful comment

Can you have a onEnter without having to add it on every Route?

All 6 comments

This is covered in the server rendering guide: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ServerRendering.md

(Sorry about the label/milestone noise above. Clicked things a little too fast there... 馃槃 )

Thank you for the quick answer! That helps but I think it does not address:

  1. How programmatically trigger a 404, 302 or 301 (and maybe other 4xx or 5xx errors) in code that asynchronously loads the data.
  2. How we can have a universal logic that works in the browser too.

To do a redirect, you just have to call the provided replace in your route hooks. To do a 404, just don't match any route (remove your * route).

How do you make it work when you have a route like /user/:id that match but after looking in the DB we find that that user does not exist?

One easy way is to do that in an onEnter hook. Just replace to a 404 route. That will trigger a redirect to a page that should give a 404. Not ideal, but generally-speaking your users should be seeing 404s that often anyways :)

Can you have a onEnter without having to add it on every Route?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ryansobol picture ryansobol  路  3Comments

misterwilliam picture misterwilliam  路  3Comments

maier-stefan picture maier-stefan  路  3Comments

davetgreen picture davetgreen  路  3Comments

yormi picture yormi  路  3Comments