How to properly implement Content Security Policy (CSP) in Next.js?

I’m implementing Content Security Policy (CSP) in a Next.js application that uses Material-UI (MUI) and Emotion, but I’m encountering style violations with MUI components.

Here’s my implementation:

1. Middleware (src/middleware.ts):

import { NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");

  const csp = `
    default-src 'self';
    script-src 'self' 'nonce-${nonce}' 'unsafe-eval';
    style-src 'self' 'nonce-${nonce}';
    img-src 'self' data: blob:;
    font-src 'self' data:;
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
  `;

  const cspValue = csp.replace(/s{2,}/g, " ").trim();

  const reqHeaders = new Headers(request.headers);
  reqHeaders.set("x-nonce", nonce);
  reqHeaders.set("Content-Security-Policy", cspValue);

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

  response.headers.set("Content-Security-Policy", cspValue);

  return response;
}

export const config = {
  matcher: [
    {
      source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
      missing: [
        { type: 'header', key: 'next-router-prefetch' },
        { type: 'header', key: 'purpose', value: 'prefetch' },
      ],
    },
  ],
};

2. Root Layout (src/app/layout.tsx):

import type { Metadata } from "next";
import "./globals.css";

import { headers } from 'next/headers';
import Script from "next/script";
import ThemeRegistry from "@/components/ThemeRegistry";


export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,`your text`
}: Readonly<{
  children: React.ReactNode;
}>) {

  const nonce = headers().get("x-nonce") || '';

  return (
    <html>
         <body>
              <Script
                  strategy="afterInteractive"
                  id="nonce-script"
                  nonce={nonce}
                  dangerouslySetInnerHTML={{
__html: `__webpack_nonce__ = ${JSON.stringify(nonce)}`
}}
              />
          <ThemeRegistry nonce={nonce}>
          {children}
        </ThemeRegistry>
         </body>
    </html>
);
}

3. ThemeRegistry (src/components/ThemeRegistry.tsx):

'use client'

import { CacheProvider } from '@emotion/react'
import { createEmotionCache } from '@/emotionCache'

export default function ThemeRegistry({ children, nonce }: { children: React.ReactNode; nonce: string }) {
  const cache = createEmotionCache(nonce)
  return <CacheProvider value={cache}>{children}</CacheProvider>
}

4. Login Component (src/views/Login.tsx):

import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';

const Login = () => {

  return (
    
<div className='flex flex-col justify-center items-center min-h-screen p-6'>
      <Card className='flex flex-col sm:w-[450px]'>
        <CardContent className='sm:p-12'>
          <div className='flex justify-center mb-6'>
            {/* Aquí iría tu Logo o texto */}
            <Typography variant='h5'>Tu Logo Aquí</Typography>
          </div>
          <div className='flex flex-col gap-1 mb-6'>
            <Typography variant='h5'>Welcome to the Portal!</Typography>
            <Typography>Please sign in to your account.</Typography>
          </div>
          {/* Aquí pondrías tus campos y botones con MUI */}
          <form className='flex flex-col gap-6'>
            {/* Ejemplo de un TextField (necesitas importarlo) */}
            {/* <TextField fullWidth label='Email' /> */}
            
            <Button fullWidth variant='contained' type='submit'>
              Login
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>

  )
}

export default Login

Dependencies:

{
  "@emotion/react": "^11.13.5",
  "@emotion/styled": "^11.13.5",
  "@mui/icons-material": "^6.1.10",
  "@mui/lab": "^6.0.0-beta.18",
  "@mui/material": "^6.1.10"
}

When accessing “http://localhost:3000/login”, I get these CSP violations in the console:

Content-Security-Policy: The page's settings blocked an inline style (style-src-attr) from being applied because it violates the following directive: "style-src 'self' 'nonce-NGYyOTBlY2ItN2RmNy00NzdkLWEzZDQtZjM4NDFkODA1Mzcy'" Source: --Paper-shadow:0px 2px 1px -1px rgba(0,0…
Content-Security-Policy: The page's settings blocked an inline style (style-src-attr) from being applied because it violates the following directive: "style-src 'self' 'nonce-NGYyOTBlY2ItN2RmNy00NzdkLWEzZDQtZjM4NDFkODA1Mzcy'"

I discovered that if I remove the Card component import (import Card from ‘@mui/material/Card’), these console errors disappear. However, I need to use the Card component in my application.

What I’ve tried:

  • Implemented ThemeRegistry with Emotion cache and nonce
  • Added webpack nonce configuration in layout.tsx
  • Set up CSP headers in middleware

I’m implementing Content Security Policy (CSP) in a Next.js application that uses Material-UI (MUI) and Emotion. I specifically want to avoid using ‘unsafe-inline’ for security reasons, but I’m encountering style violations with MUI components.

  • I would like to maintain strict security by avoiding ‘unsafe-inline’ in my CSP directives
  • Looking for a solution that works with nonces or hashes, rather than ‘unsafe-inline’

I’ve spent quite a bit of time researching and trying different approaches. Any guidance on how to properly configure CSP to work with MUI’s Card component while maintaining security would be greatly appreciated!

Thank you in advance for your help! 🙂

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật