Content Security Policy (CSP) middleware issue
Answered
Chinese Chongqing Dog posted this in #help-forum
Chinese Chongqing DogOP
Hey, i have a issue where my button stops working as intended, i made a small template to better visualize the issue, on my page i have this button:
and this is my middleware (CSP):
now my issue is that if i click the button the
"use client";
export default function Home() {
const handleClick = () => {
alert('kaboom');
};
return (
<div>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
and this is my middleware (CSP):
import { NextRequest, NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const cspHeader = `
script-src 'nonce-{nonce}' 'strict-dynamic';
object-src 'none';
base-uri 'none';
`
// Replace newline characters and spaces
const contentSecurityPolicyHeaderValue = cspHeader
.replace(/\s{2,}/g, ' ')
.trim()
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-nonce', nonce)
requestHeaders.set(
'Content-Security-Policy',
contentSecurityPolicyHeaderValue
)
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
})
response.headers.set(
'Content-Security-Policy',
contentSecurityPolicyHeaderValue
)
return response
}
now my issue is that if i click the button the
handleClick
will not get executed in combination with the CSP. any ideas what could cause this and how to fix this?Answered by Chinese Chongqing Dog
i dint figure it out yet, can you give me a template how i could implement this? the only solution i found until now is a Script in the layout which i pass the nonce too together with the rule strict-dynamic, but this doesent feel correct lol
12 Replies
Chinese Chongqing DogOP
what would i need to change so the button would actually work tho, if i just have it for one page the button would still not work for this page?
should fix it

@Chinese Chongqing Dog
@American Sable should fix it
Chinese Chongqing DogOP
i dint figure it out yet, can you give me a template how i could implement this? the only solution i found until now is a Script in the layout which i pass the nonce too together with the rule strict-dynamic, but this doesent feel correct lol
Answer
@American Sable https://nextjs.org/docs/pages/guides/content-security-policy
Chinese Chongqing DogOP
i cant get the nonce on the site if its a client component
@Chinese Chongqing Dog i dint figure it out yet, can you give me a template how i could implement this? the only solution i found until now is a Script in the layout which i pass the nonce too together with the rule strict-dynamic, but this doesent feel correct lol
Chinese Chongqing DogOP
this seems to actually be the solution
@Chinese Chongqing Dog this seems to actually be the solution
American Sable
great to hear
glad i could help