erikras / react-redux-universal-hot-example

A starter boilerplate for a universal webapp using express, react, redux, webpack, and react-transform
MIT License
12.01k stars 2.5k forks source link

Overriding HTTP status code #729

Open eirslett opened 8 years ago

eirslett commented 8 years ago

It would be nice if we could override the status code to 404 when doing server-side rendering, e.g. if a route matches, but the document we're looking for doesn't exist. Is something like that possible today?

Dattaya commented 8 years ago

Linking to a related discussion: #518 In my project (but it's not based on this boilerplate) if an action has a role primary and it failed to load, I re-throw the status in redux middleware that's responsible for fetching data:

...
    .catch(error => {
      next({...rest, error, type: FAILURE});

      if (action.role === 'primary') {
        throw {status: error.status};
      }
...

catch and pass it down on the server with catch(err => err), and then in getStatus method I have a check similar to what is present here, to see if the requested url didn't match any react route: routes.reduce((prev, curr) => curr.status || prev), but also check if passed err has a status field:

  if (errOrRes && errOrRes.status) {
    return errOrRes.status;
  }

Inside the component I return NotFound page if the required props are missing, e.g.:

    if (!this.props.product) {
      return <NotFound/>
    }
trueter commented 8 years ago

It would be nice if we could override the status code to 404 when doing server-side rendering, e.g. if a route matches, but the document we're looking for doesn't exist. Is something like that possible today?

Because of this, we can pass status to the fulfilling object like this.

export default function loadDocument( req ) {
  return getDocument( req.params.id ).then( result => {
    if( result.rows.length === 0 ) 
      return { status: 404 }
    else 
      return { 
        // status: 200, // assumed by default
        results: result.rows
      }
  })
}
eirslett commented 8 years ago

@trueter That's possible for the API only, not the web application...

trueter commented 8 years ago

What about getStatusFromRoutes ?

eirslett commented 8 years ago

Yes, something with getStatusFromRoutes. But that function only picks up the status defined in routes, which is hard-coded.

skywickenden commented 8 years ago

There is a solution to this at https://github.com/erikras/react-redux-universal-hot-example/issues/850