Skip to content

Commit 0236e18

Browse files
authored
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.
1 parent 3cd122d commit 0236e18

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

docs/01-app/02-guides/content-security-policy.mdx

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,54 @@ export const config = {
172172

173173
### Reading the nonce
174174

175-
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):
175+
<PagesOnly>
176+
You can provide the nonce to your page using
177+
[`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props):
178+
179+
```tsx filename="pages/index.tsx" switcher
180+
import Script from 'next/script'
181+
182+
import type { GetServerSideProps } from 'next'
183+
184+
export default function Page({ nonce }) {
185+
return (
186+
<Script
187+
src="https://www.googletagmanager.com/gtag/js"
188+
strategy="afterInteractive"
189+
nonce={nonce}
190+
/>
191+
)
192+
}
193+
194+
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
195+
const nonce = req.headers['x-nonce']
196+
return { props: { nonce } }
197+
}
198+
```
199+
200+
```jsx filename="pages/index.jsx" switcher
201+
import Script from 'next/script'
202+
export default function Page({ nonce }) {
203+
return (
204+
<Script
205+
src="https://www.googletagmanager.com/gtag/js"
206+
strategy="afterInteractive"
207+
nonce={nonce}
208+
/>
209+
)
210+
}
211+
212+
export async function getServerSideProps({ req }) {
213+
const nonce = req.headers['x-nonce']
214+
return { props: { nonce } }
215+
}
216+
```
217+
218+
</PagesOnly>
219+
220+
<AppOnly>
221+
222+
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):
176223

177224
```tsx filename="app/page.tsx" switcher
178225
import { headers } from 'next/headers'
@@ -208,6 +255,8 @@ export default async function Page() {
208255
}
209256
```
210257

258+
</AppOnly>
259+
211260
## Without Nonces
212261

213262
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:

0 commit comments

Comments
 (0)