Appearance
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:
jsx
// import App from 'next/app'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
export default MyAppThe 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 ifpages/_app.jsdidn't exist before. - Adding a custom
getInitialPropsin yourAppwill disable Automatic Static Optimization in pages without Static Generation. - When you add
getInitialPropsin your custom app, you mustimport App from "next/app", callApp.getInitialProps(appContext)insidegetInitialPropsand merge the returned object into the return value. Appcurrently does not support Next.js Data Fetching methods likegetStaticPropsorgetServerSideProps.
TypeScript
If you’re using TypeScript, take a look at our TypeScript documentation.
Related
For more information on what to do next, we recommend the following sections:
