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

Need help on a project?

I'm available for freelance work.
Send me an email! Or find out more about my services.