Max SchmittMS
18th September 2020

Next.js: How to show the default 404 page

Next.js comes with a pretty nice 404 page out of the box. By default it gets shown when Next.js can't find any route for the path you're trying to access.

You can also show it programmatically by using the <ErrorPage /> component.

import ErrorPage from 'next/error'
async function getInitialProps({ query, res }) {
const blogPost = await api.fetchBlogPost(query.slug)
if (!blogPost) {
if (res) {
res.statusCode = 404
}
return { errorStatus: 404 }
}
return { blogPost }
}
function BlogPost({ errorStatus, blogPost }) {
if (errorStatus) {
return <ErrorPage statusCode={errorStatus} />
}
return <BlogPost blogPost={blogPost} />
}
BlogPost.getInitialProps = getInitialProps
export default BlogPost

If you have a lot of pages where 404s can occur, you might want to move the ErrorPage rendering to _app.js.

Optional: Show error page in _app.js

You can also extend _app.js to magically show the error page if the initial props of a page have an errorStatus property:

import ErrorPage from 'next/error'
import App from 'next/app'
async function getInitialProps(appContext) {
const { res } = appContext.ctx
const appProps = await App.getInitialProps(appContext)
if (appProps.pageProps?.errorStatus && res) {
res.statusCode = appProps.pageProps.errorStatus
}
return {
...appProps
}
}
function MyApp({ Component, pageProps }) {
if (pageProps?.errorStatus) {
return <ErrorPage statusCode={pageProps.errorStatus} />
}
return <Component {...pageProps} />
}
MyApp.getInitialProps = getInitialProps
export default MyApp
Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.