Next.js Discord

Discord Forum

Trying to read `nonce` header in `_document.tsx` file

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
What am I doing wrong?

import {
  Html,
  Head,
  Main,
  NextScript,
  DocumentInitialProps,
  DocumentContext,
} from 'next/document'

function Document(props: DocumentInitialProps & { nonce: string }) {
  return (
    <Html lang="pt-br">
      <Head nonce={props.nonce} />
      <body>
        <Main />
        <NextScript nonce={props.nonce} />
      </body>
    </Html>
  )
}

Document.getInitialProps = async (ctx: DocumentContext) => {
  const initialProps = await Document.getInitialProps(ctx)
  const nonce = ctx.req.headers['x-nonce']

  return { ...initialProps, nonce }
}

export default Document

6 Replies

Asian black bearOP
BTW: this is a Nextra project, which currently does not support the app directory
What is the error?
Or what problem are you facing?
Asian black bearOP
These are client-side errors
And these happened on the server
@Clown Or what problem are you facing?
Asian black bearOP
And here's the middleware

import { NextRequest, NextResponse } from 'next/server'

export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
  const cspHeader = `
    default-src 'self';
    script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
    style-src 'self' 'nonce-${nonce}';
    img-src 'self' blob: data:;
    font-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
    block-all-mixed-content;
    upgrade-insecure-requests;
`

  const requestHeaders = new Headers(request.headers)
  requestHeaders.set('x-nonce', nonce)
  requestHeaders.set(
    'Content-Security-Policy',
    // Replace newline characters and spaces
    cspHeader.replace(/\s{2,}/g, ' ').trim()
  )

  const response = NextResponse.next({
    headers: requestHeaders,
    request: {
      headers: requestHeaders,
    },
  })

  response.headers.delete('x-powered-by')

  return response
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}