How to add nonce to inline styles and scripts in Next.js? – Next.js

by
Ali Hasan
next.js next.js13

Quick Fix: In middleware.ts, define the content-security-policy header to include the nonce attribute. This header will be parsed by Next.js to extract the nonce value, which will then be added to the generated HTML tags. Additionally, consider implementing a custom request header to read the nonce value in your pages.

The Problem:

In Next.js, when using a Content-Security-Policy that restricts inline styles and scripts, there is a need to add a nonce to enable their execution. However, the Next.js documentation does not provide guidance on how to add nonces to inline styles and scripts, particularly in the context of React Server Components (RSC).

The Solutions:

Solution 1: Use a Middleware Function and Custom Request Header

Follow these steps to add a nonce to styles and scripts with a middleware function and a custom request header:

1. Define a middleware function in your `pages/api/middleware.ts` file:
“`ts
import { NextResponse } from ‘next/server’;
import type { NextRequest } from ‘next/server’;

export function middleware(request: NextRequest) {
// Generate a unique nonce value
const nonce = crypto.randomUUID();

// Create a Content-Security-Policy header with the nonce
const csp = script-src 'nonce-${nonce}';;

// Clone the request headers
const requestHeaders = new Headers(request.headers);

// Set the CSP header so that Next.js can read it and generate tags with the nonce
requestHeaders.set(‘content-security-policy’, csp);

// Create a new response with the modified request headers
const response = NextResponse.next({
request:
});

// Also set the CSP header in the response so that it is outputted to the browser
response.headers.set(‘content-security-policy’, csp);

return response;
}


2. Add a custom request header to read the nonce value in your pages:
```ts
requestHeaders.set('x-nonce', nonce);
  1. Ensure that the nonce value is generated differently for each page load, as recommended by the MDN documentation.

This solution only works with dynamic routes, not with static rendering.

Solution 2: Adding a nonce to inline styles and scripts

To add a nonce to inline styles and scripts in Next.js, you can use the `nonce` attribute when rendering the elements.

<style nonce="my-nonce">
  /* Your styles */
</style>

<script nonce="my-nonce">
  // Your script
</script>

In Next.js, the `nonce` attribute is automatically applied to inline styles and scripts when using the `styled-jsx` library.

Q&A

How to add nonce to inline styles and scripts in Next.js?

You need to define the "content-security-policy" header in the middleware.ts file (works with [email protected] and higher).

How to add nonce with custom request header?

Use "requestHeaders.set(‘x-nonce’, nonce);" to set custom request Header.

Impact of adding nonce on lighthouse report?

It will still complain ‘Consider adding unsafe-inline’ with severity Medium.

Video Explanation:

The following video, titled "XSS Protection with Content Security Policy - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Geoff Appleby If unexpected inline JavaScript was added to a WYSIWYG field on your ... What's Next(js) for Drupal? Bay Area Drupal Camp•2.5K views.