vercel / next.js

The React Framework
https://nextjs.org
MIT License
122.51k stars 26.22k forks source link

Middleware added Nonce attributes missing from TypeScript production builds #66871

Open andymagill opened 1 week ago

andymagill commented 1 week ago

Link to the code that reproduces this issue

https://github.com/andymagill/csp-middleware-nextjs-bug/tree/main

To Reproduce

  1. Create a local copy of the reproduction template via yarn create next-app --example reproduction-template reproduction-app
  2. Add the middleware.ts TypeScript (not JS) file from the documentation : https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
  3. Build the project via yarn install then yarn run build then yarn run start
  4. Open the browser console to see CSP errors for each bundle. Alternatively, inspect the source of the server response to confirm bundles have no nonce attribute.

Current vs. Expected behavior

Current behavior: nonce attributes are missing from bundles Expected behavior: nonce attributes are present on bundles

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Pro
  Available memory (MB): 16093
  Available CPU cores: 16
Binaries:
  Node: 20.11.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.4 // Latest available version is detected (14.2.4).
  eslint-config-next: N/A
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 4.9.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Documentation, Middleware, TypeScript

Which stage(s) are affected? (Select all that apply)

next build (local)

Additional context

This behavior appears to be specific to production builds of next.js typescript middleware. Running yarn run dev in the example repo works fine and correctly adds the nonce. The "with-strict-csp" example with the middleware.JS (not ts) also correctly adds the nonce on production builds.

Currently, I see no way to add nonces to Next.JS TypeScript projects using the documented methods.