Custom App

Next.js uses the App component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like:

  • Persisting layout between page changes
  • Keeping state when navigating pages
  • Custom error handling using componentDidCatch
  • Inject additional data into pages
  • Add global CSS

To override the default App, create the file ./pages/_app.js as shown below:

  1. // import App from 'next/app'
  2. function MyApp({ Component, pageProps }) {
  3. return <Component {...pageProps} />
  4. }
  5. // Only uncomment this method if you have blocking data requirements for
  6. // every single page in your application. This disables the ability to
  7. // perform automatic static optimization, causing every page in your app to
  8. // be server-side rendered.
  9. //
  10. // MyApp.getInitialProps = async (appContext) => {
  11. // // calls page's `getInitialProps` and fills `appProps.pageProps`
  12. // const appProps = await App.getInitialProps(appContext);
  13. //
  14. // return { ...appProps }
  15. // }
  16. export default MyApp

The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page.

pageProps is an object with the initial props that were preloaded for your page by one of our data fetching methods, otherwise it’s an empty object.

The App.getInitialProps receives a single argument called context.ctx. It’s an object with the same set of properties as the context object in getInitialProps.

Caveats

  • If your app is running and you added a custom App, you’ll need to restart the development server. Only required if pages/_app.js didn’t exist before.
  • Adding a custom getInitialProps in your App will disable Automatic Static Optimization in pages without Static Generation.
  • When you add getInitialProps in your custom app, you must import App from "next/app", call App.getInitialProps(appContext) inside getInitialProps and merge the returned object into the return value.
  • App currently does not support Next.js Data Fetching methods like getStaticProps or getServerSideProps.

TypeScript

If you’re using TypeScript, take a look at our TypeScript documentation.

For more information on what to do next, we recommend the following sections:

Automatic Static OptimizationNext.js automatically optimizes your app to be static HTML whenever possible. Learn how it works here.

Custom Error PageLearn more about the built-in Error page.