Unverified Commit 0236e185 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix CSP docs (#78937)

This is erroneously showing the app router docs for pages router,
however nonce handling was not added to pages router (support is being
added in #78936) and the included examples are using server components.
parent 3cd122d8
...@@ -172,7 +172,54 @@ export const config = { ...@@ -172,7 +172,54 @@ export const config = {
### Reading the nonce ### Reading the nonce
You can now read the nonce from a [Server Component](/docs/app/building-your-application/rendering/server-components) using [`headers`](/docs/app/api-reference/functions/headers): <PagesOnly>
You can provide the nonce to your page using
[`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props):
```tsx filename="pages/index.tsx" switcher
import Script from 'next/script'
import type { GetServerSideProps } from 'next'
export default function Page({ nonce }) {
return (
<Script
src="https://www.googletagmanager.com/gtag/js"
strategy="afterInteractive"
nonce={nonce}
/>
)
}
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
const nonce = req.headers['x-nonce']
return { props: { nonce } }
}
```
```jsx filename="pages/index.jsx" switcher
import Script from 'next/script'
export default function Page({ nonce }) {
return (
<Script
src="https://www.googletagmanager.com/gtag/js"
strategy="afterInteractive"
nonce={nonce}
/>
)
}
export async function getServerSideProps({ req }) {
const nonce = req.headers['x-nonce']
return { props: { nonce } }
}
```
</PagesOnly>
<AppOnly>
You can read the nonce from a [Server Component](/docs/app/building-your-application/rendering/server-components) using [`headers`](/docs/app/api-reference/functions/headers):
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
import { headers } from 'next/headers' import { headers } from 'next/headers'
...@@ -208,6 +255,8 @@ export default async function Page() { ...@@ -208,6 +255,8 @@ export default async function Page() {
} }
``` ```
</AppOnly>
## Without Nonces ## Without Nonces
For applications that do not require nonces, you can set the CSP header directly in your [`next.config.js`](/docs/app/api-reference/config/next-config-js) file: For applications that do not require nonces, you can set the CSP header directly in your [`next.config.js`](/docs/app/api-reference/config/next-config-js) file:
......
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