Customizing App, Document and Error Pages in NextJS

Next.js uses the App component to initialize pages. You can override it creating a ./pages/_app.js file if, for example. you want to do some of the following things:

  • Persisting layout between page changes
  • Keeping state when navigating pages
  • Custom error handling using componentDidCatch
  • Inject additional data into pages
  • Add global CSS
function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page.

Customizing Document

You can create a ./pages/_document.js to augment your application’s <html> and <body> tags.

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

<Html>, <Head />, <Main /> and <NextScript /> are required for the page to be properly rendered. The <Head /> component used here is not the same one from next/head. To set individual <title> tags, you should use next/head in your pages or components.

Document is only rendered in the server, event handlers like onClick won’t work.

Custom Error pages

Next.js provides a static 404 page by default without having to add any additional files. To create a custom 404 page you can create a pages/404.js file. This file is statically generated at build time.

// pages/404.js
export default function Custom404() {
  return <h1>404 - Page Not Found</h1>
}

Same goes for 500 error page

// pages/500.js
export default function Custom500() {
  return <h1>500 - Server-side error occurred</h1>
}

500 errors are handled both client-side and server-side by the Error component. If you wish to override it, define the file pages/_error.js and add the following code:

function Error({ statusCode }) {
  return (
    <p>
      {statusCode
        ? `An error ${statusCode} occurred on server`
        : 'An error occurred on client'}
    </p>
  )
}

Error.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404
  return { statusCode }
}

export default Error

About Author

Mathias Bothe To my job profile

I am Mathias, born 39 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 15 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.