Next.js return the 404 error page in getInitialProps

next.js custom 404 page
next js error boundary
nextjs getinitialprops
next js custom server
next js state management
next js redirect in getinitialprops
next js serverless
next js static files

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

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.


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.

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) {
      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.

[Suggestion] ability for getInitialProps to return a 404 error · Issue , I have a project at the moment that uses nextjs embedded in an express server. I have a page called event.js and I route /event/:eventId to  As title mentioned, how can I redirect client to 404 in getInitialProps()? for example, I cannot fetch results from API then the page should display "Not Found".

Implement your getInitialProps along the lines of:

    static async getInitialProps(context) {
        const {res} = context;


        if ([something went wrong]) {
            if (res) {
                res.statusCode = 404;

            return {
                err: {
                    statusCode: 404

Then in render() check if err is defined in state, in which case return the ErrorPage (default or custom one, depending on your implementation) and that's it! The statusCode inside err is just for more granular message on the ErrorPage so it needs to be passed for it as props.

Next.js return the 404 error page in getInitialProps, Implement your getInitialProps along the lines of: static async getInitialProps(context) { const {res} = context; if ([something went wrong]) { if (res) { res. statusCode = 404; } return { err: { statusCode: 404 }, }; } There is no way to render the default error page in this situation, but you can do the following for now. static getInitialProps ({ res }) { if (res) { res. statusCode = 404 res. end ('Not found') return } } nkzawa added the Type: Bug label on Jan 12, 2017 iest commented on Jan 23, 2017 •

import App, { Container } from 'next/app'
import React from 'react'
import Head from 'next/head'
import * as Sentry from '@sentry/node'
import Error from './_error'


class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}
    let e
    if (Component.getInitialProps) {
      try {
        pageProps = await Component.getInitialProps(ctx)
      } catch (error) {
        e = error
        Sentry.captureException(error) //report to sentry
    return { pageProps, e }

  render() {
    const { Component, pageProps, e } = this.props
    if (e) {
      return <Error /> // customize your error page
    return (
          <title> Your title</title>
        <Component {...pageProps} />

export default MyApp

This works like a charm ~ just try catch in next/app, then it works for all the pages

Learning NextJs, For this day I want to talk about how NextJs deal with Http Errors. The way to customize not only the design of the error page but also the actual status code sent to the clients. Let's assume we have. function getInitialProps({ query, res }) { const { id } return { user: user || {}, statusCode: user ? 200 : 404 }; import withErrorPage from '../lib/with-error-page.js' class SomePage extends React.Component { static async getInitialProps () { return { statusCode: 404 } } render () { return < div >What is rendered when there's no 404</ div > } } export default withErrorPage (SomePage) If no statusCode is provided the component render is executed.

Advanced Features: Custom `Document`, js pages skip the definition of the surrounding document's markup. A custom Document can also include getInitialProps for expressing asynchronous server-  @andreyvital Yes exactly. It is more for classic REST calls. Apollo is a bit special because the call is executed in a mix of getInitialProps and render (cf react-apollo implementation).

Next js error page 404, getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 404 return { statusCode } } export default Error. pages/_error.js  For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router. Context Object. getInitialProps receives a single argument called context, it's an object with the following properties: pathname - Current

Routing, 0. js will automatically load the 404 error page or 500 error 15 May 2018 Implicit page's path. server-side ( NextJS + Express) via @sentry/node I get an error about getInitialProps can only be added to the default component exported by a  I'm using getInitialProps in next.js This my code: static getInitialProps( ctx ) { console.log(ctx.isServer); return{} } Why can't I find isServer?

  • thx, works for me too as need)