How to properly use Nonce in Next.js CSP configuration?
Unanswered
Chalcid wasp posted this in #help-forum
Chalcid waspOP
Here is my CSP configuration:
Whenever, I use Nonce it is not appearing in the inline scripts & styles generated by Next.js. And all my scripts & styles are blocked because of this.
export default function withCSP(_middleware: CustomMiddleware) {
return async (request: NextRequest, _event: NextFetchEvent, _response: NextResponse) => {
const nonce = Buffer?.from(crypto?.randomUUID())?.toString("base64");
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${process.env.NODE_ENV === "development" && "'unsafe-eval'"};
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data:;
font-src 'self' https://fonts.gstatic.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
block-all-mixed-content;
upgrade-insecure-requests;
`;
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;
};
}
Whenever, I use Nonce it is not appearing in the inline scripts & styles generated by Next.js. And all my scripts & styles are blocked because of this.
4 Replies
Black Mouth Cur
Have you found the solutions?
Chalcid waspOP
Nope
American Crocodile
Yooo masters! please anyone tell me there is someone who solved this ❤️
How can we have that nonce properly set on the chunks?
How can we have that nonce properly set on the chunks?
Chalcid waspOP
No clue yet