Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js return the 404 error page in getInitialProps

Currently I am following this example on how to redirect users in getInitialProps

https://github.com/zeit/next.js/wiki/Redirecting-in-%60getInitialProps%60

The problem is, if I want to return 404 like this, it will return a blank page instead of the usual Next.js 404 error page.

context.res.writeHead(404)
context.res.end();

Please note I know using ExpressJs and using statuscode 404 works, however, for this project I am not allowed to use ExpressJs so I need to use typical nodejs writeHead to do it.

like image 752
Thomas Charlesworth Avatar asked Dec 01 '17 04:12

Thomas Charlesworth


2 Answers

In order to do that, you’ll have to render the Error page in your page.

You can do something like this:

import React from 'react'
import ErrorPage from 'next/error'

class HomePage extends React.Component {
  static async getInitialProps(context) {
    try {
      const data = await retrieveSomeData()
      return { data }
    } catch (err) {
      // Assuming that `err` has a `status` property with the HTTP status code.
      if (context.res) {
        context.res.writeHead(err.status)
      }
      return { err: { statusCode: err.status } }
    }
  }

  render() {
    const { err, data } = this.props

    if (err) {
      return <ErrorPage statusCode={err.statusCode} />
    }

    /*
     * return <Something data={data} />
     */
  }
}

If you have a custom error page, instead of importing next/error, you’ll have to import your custom _error page.

like image 199
Bertrand Marron Avatar answered Oct 13 '22 00:10

Bertrand Marron


Next v10 allows to return 404 page (not with props, but just plain as it is below)

  if (!checkItem) {
    return {
      notFound: true
    }
  }

Full code that works for me: ✅✅✅

export const getServerSideProps = wrapper.getServerSideProps(async ({ req, res, locale, query, store }) => {
  const { productId, categoryId } = query
   
  const checkItem = await getProductBySlugSSR(productId, categoryId, store)

  if (!checkItem) {
    return { // <-----------------does the trick here!!
      notFound: true
    }
  }
    
  return {
    props: {
      ...await serverSideTranslations(locale, ['common']),
    }
  }
})

Documentation: https://nextjs.org/blog/next-10#notfound-support

like image 23
Alex K - JESUS first Avatar answered Oct 12 '22 23:10

Alex K - JESUS first