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! 🙂