GN.
GN.

Reputation: 9819

NextJS: 404 page when Express endpoint returns 404?

and API endpoint (Express) sends 404 .
return res.status(404).json({ message: 'Not Found !!!' })

In the _app Component

static async getInitialProps({ Component, ctx }) {
    try {
      const pageProps = Component.getInitialProps
        ? await Component.getInitialProps(ctx)
        : {}

      const statusCode = ctx.res && ctx.res.statusCode

      return {
        pageProps,
        statusCode
      }
     } catch (err) {
       // What to do here?
     }

The app component calls getInitialProps in another Component... here is calls the API which will return a 404 status.

static async getInitialProps(ctx) {
   try {
      const response = await axios.get(route.API_POST(id))
      // do something with response
    } catch (err) {
      //???????
    }
}

Only, it does not. It returns 200.

How do you render a 404 page in NextJS when the Express endpoint returns a 404 status?

Upvotes: 0

Views: 2344

Answers (1)

giggi__
giggi__

Reputation: 1963

In the custom server you are doing:

app.render(req, res, page, params)

If you modify the res object in express changing the statusCode to 404, in the route component in NextJS you will have the res object and the statusCode property. If res.statusCode is never 404, try to override it in getInitialProps

static async getInitialProps({ Component, ctx }) {
    try {
      const pageProps = Component.getInitialProps
        ? await Component.getInitialProps(ctx)
        : {}

      const statusCode = ctx.res && ctx.res.statusCode

     ctx.res.statusCode = 404

      return {
        pageProps,
        statusCode
      }
     } catch (err) {
       // What to do here?
       // Here you cannot do anything because 
       // you don’t have any throw in the previous statements
     }
}

I have noticed that the code above is about the getInitialProps of _app.js, i don’t know if this works in this component. However, try to add a route and do:

static getInitialProps({ res }) {
  if (res) {
    res.statusCode = 404
  }

  return {}
}

Upvotes: 1

Related Questions