this post was submitted on 30 Jul 2023
4 points (83.3% liked)

React

935 readers
1 users here now

A community for discussing anything related to the React UI framework and it's ecosystem.

https://react.dev/

Wormhole

[email protected]

Icon base by Skoll under CC BY 3.0 with modifications to add a gradient

founded 1 year ago
MODERATORS
 

Using react router and have a route definition:

  {
       path: '/',
       element: <Root pageTitle={pageTitle} />,
       errorElement: <ErrorPage setPageTitle={updatePageTitle} />,
       children: [
          ...
          {
             path: '*',
             element: <ErrorPage setPageTitle={updatePageTitle} />,
             loader: async () => {
                console.log('throwing a 404');
                throw new Response('Not Found', { status: 404 });
             },
          },
       ],
    },

This does show me the 404 page how I want, but http status is reported as 200. How do I properly throw it as a 404?

It seems not to trigger the loader (console log does not appear), or is there another method to throw a 404 and show a pretty page?

top 1 comments
sorted by: hot top controversial new old
[–] GregoryTheGreat 3 points 1 year ago

React and react-router-dom operate entirely on the client side, so they don’t have the ability to set HTTP status codes like 404, which are a server-side concept. You can certainly display a “Not Found” page in React when a user tries to access a route that doesn’t exist, but the HTTP status code will still be 200 because the server successfully sent the HTML and JavaScript to the client. If you want to return a 404 status code, you’d need to handle that on the server side. For example, in Express.js, you could add a catch-all route handler after all your other routes that sends a 404 status. If you’re using server-side rendering or static site generation (like Next.js), you could potentially return a 404 status code along with a “Not Found” page. But with a purely client-side React app, it’s not possible.