Unverified Commit c6b163f3 authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

docs: Update `_app` and `_document` (#52479)

- Remove specific TypeScript sections and add JS/TS code block toggles
- Consolidate "Good to know" information into sections
- Add links back to incrementally adopting the App Router when trying to
use escape hatches
- Add better TS example for `getInitialProps` (even tho it's not
recommended, still helpful)
parent 9ea188a0
......@@ -5,14 +5,23 @@ description: Control page initialization and add a layout that persists for all
Next.js uses the `App` component to initialize pages. You can override it and control the page initialization and:
- Persist layouts between page changes
- Keeping state when navigating pages
- Created a shared layout between page changes
- Inject additional data into pages
- [Add global CSS](/docs/pages/building-your-application/styling)
To override the default `App`, create the file `pages/_app.js` as shown below:
## Usage
```jsx filename="pages/_app.js"
To override the default `App`, create the file `pages/_app` as shown below:
```tsx filename="pages/_app.tsx" switcher
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
```
```jsx filename="pages/_app.jsx" switcher
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
......@@ -22,15 +31,59 @@ The `Component` prop is the active `page`, so whenever you navigate between rout
`pageProps` is an object with the initial props that were preloaded for your page by one of our [data fetching methods](/docs/pages/building-your-application/data-fetching), 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](/docs/pages/api-reference/functions/get-initial-props#context-object) in `getInitialProps`.
> **Good to know**
>
> - 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.
> - `App` does not support Next.js [Data Fetching methods](/docs/pages/building-your-application/data-fetching) like [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) or [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props).
## `getInitialProps` with `App`
Using [`getInitialProps`](/docs/pages/api-reference/functions/get-initial-props) in `App` will disable [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) for pages without [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props).
**We do not recommend using this pattern.** Instead, consider [incrementally adopting](/docs/app/building-your-application/upgrading/app-router-migration) the App Router, which allows you to more easily fetch data for [pages and layouts](/docs/app/building-your-application/routing/pages-and-layouts).
```tsx filename="pages/_app.tsx" switcher
import App, { AppContext, AppInitialProps, AppProps } from 'next/app'
### Caveats
type AppOwnProps = { example: string }
- 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`](/docs/pages/api-reference/functions/get-initial-props) in your `App` will disable [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization) in pages without [Static Generation](/docs/pages/building-your-application/data-fetching/get-static-props).
- 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` does not support Next.js [Data Fetching methods](/docs/pages/building-your-application/data-fetching) like [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) or [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props). If you need global data fetching, consider [incrementally adopting the `app/` directory](/docs/app/building-your-application/upgrading).
export default function MyApp({
Component,
pageProps,
example,
}: AppProps & AppOwnProps) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}
MyApp.getInitialProps = async (
context: AppContext
): Promise<AppOwnProps & AppInitialProps> => {
const ctx = await App.getInitialProps(context)
return { ...ctx, example: 'data' }
}
```
### TypeScript
```jsx filename="pages/_app.jsx" switcher
import App from 'next/app'
If you’re using TypeScript, take a look at [our TypeScript documentation](/docs/pages/building-your-application/configuring/typescript#custom-app).
export default function MyApp({ Component, pageProps, example }) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}
MyApp.getInitialProps = async (context) => {
const ctx = await App.getInitialProps(context)
return { ...ctx, example: 'data' }
}
```
......@@ -3,16 +3,16 @@ title: Custom Document
description: Extend the default document markup added by Next.js.
---
A custom `Document` can update the `<html>` and `<body>` tags used to render a [Page](/docs/pages/building-your-application/routing/pages-and-layouts). This file is only rendered on the server, so event handlers like `onClick` cannot be used in `_document`.
A custom `Document` can update the `<html>` and `<body>` tags used to render a [Page](/docs/pages/building-your-application/routing/pages-and-layouts).
To override the default `Document`, create the file `pages/_document.js` as shown below:
To override the default `Document`, create the file `pages/_document` as shown below:
```jsx
```tsx filename="pages/_document.tsx" switcher
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Html lang="en">
<Head />
<body>
<Main />
......@@ -23,19 +23,26 @@ export default function Document() {
}
```
The code above is the default `Document` added by Next.js. Custom attributes are allowed as props. For example, we might want to add `lang="en"` to the `<html>` tag:
```jsx
<Html lang="en">
```
Or add a `className` to the `body` tag:
```jsx filename="pages/_document.jsx" switcher
import { Html, Head, Main, NextScript } from 'next/document'
```jsx
<body className="bg-white">
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
`<Html>`, `<Head />`, `<Main />` and `<NextScript />` are required for the page to be properly rendered.
> **Good to know**
>
> - `_document` is only rendered on the server, so event handlers like `onClick` cannot be used in this file.
> - `<Html>`, `<Head />`, `<Main />` and `<NextScript />` are required for the page to be properly rendered.
## Caveats
......@@ -45,17 +52,24 @@ Or add a `className` to the `body` tag:
## Customizing `renderPage`
> **Good to know**: This is advanced and only needed for libraries like CSS-in-JS to support server-side rendering. This is not needed for built-in `styled-jsx` support.
For [React 18](/docs/getting-started/react-essentials) support, we recommend avoiding customizing `getInitialProps` and `renderPage`, if possible.
Customizing `renderPage` is advanced and only needed for libraries like CSS-in-JS to support server-side rendering. This is not needed for built-in `styled-jsx` support.
The `ctx` object shown below is equivalent to the one received in [`getInitialProps`](/docs/pages/api-reference/functions/get-initial-props#context-object), with the addition of `renderPage`.
**We do not recommend using this pattern.** Instead, consider [incrementally adopting](/docs/app/building-your-application/upgrading/app-router-migration) the App Router, which allows you to more easily fetch data for [pages and layouts](/docs/app/building-your-application/routing/pages-and-layouts).
```jsx
import Document, { Html, Head, Main, NextScript } from 'next/document'
```tsx filename="pages/_document.tsx" switcher
import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
DocumentInitialProps,
} from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const originalRenderPage = ctx.renderPage
// Run the React rendering logic synchronously
......@@ -75,7 +89,7 @@ class MyDocument extends Document {
render() {
return (
<Html>
<Html lang="en">
<Head />
<body>
<Main />
......@@ -89,24 +103,45 @@ class MyDocument extends Document {
export default MyDocument
```
> **Good to know**: `getInitialProps` in `_document` is not called during client-side transitions.
## TypeScript
```jsx filename="pages/_document.jsx" switcher
import Document, { Html, Head, Main, NextScript } from 'next/document'
You can use the built-in `DocumentContext` type and change the file name to `./pages/_document.tsx` like so:
class MyDocument extends Document {
static async getInitialProps(ctx) {
const originalRenderPage = ctx.renderPage
```tsx
import Document, { DocumentContext, DocumentInitialProps } from 'next/document'
// Run the React rendering logic synchronously
ctx.renderPage = () =>
originalRenderPage({
// Useful for wrapping the whole react tree
enhanceApp: (App) => App,
// Useful for wrapping in a per-page basis
enhanceComponent: (Component) => Component,
})
class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
// Run the parent `getInitialProps`, it now includes the custom `renderPage`
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
```
> **Good to know**
>
> - `getInitialProps` in `_document` is not called during client-side transitions.
> - The `ctx` object for `_document` is equivalent to the one received in [`getInitialProps`](/docs/pages/api-reference/functions/get-initial-props#context-object), with the addition of `renderPage`.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment