Secure App Shell
Updated
IntermediateWhat you'll learn
~35 min- Order CSS layers so Tailwind utilities override MUI styles without !important
- Generate a per-request CSP nonce (a one-time token that marks a style or script as allowed by the Content Security Policy header) in proxy.ts and read it with async headers()
- Pass the nonce to AppRouterCacheProvider and write a browser test that proves it lands on every style tag
- Record the dark-mode default as an agency decision with a reason
Two styling systems, one cascade, one policy
The reference app uses MUI for structured components (data grid, dialog, autocomplete) and Tailwind for layout utilities. MUI styles itself with Emotion, which writes style elements into the page at runtime. A Content Security Policy (CSP, a response header that lists which scripts and styles the browser may run) that forbids inline styles will block those elements unless each one carries the nonce the header names.
This lesson builds the shell (app bar, navigation, content area) so that three things hold and a test proves each: Tailwind utilities win over MUI defaults, the CSP names no unsafe-inline for styles, and every style element carries the response’s nonce. Versions are the pinned majors in the baseline table of Lesson 2.
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| MUI and Tailwind fight over specificity | CSS layers, MUI in its own layer below utilities (the alternative: scope Tailwind with a prefix and keep MUI outside layers) | Unchanged on every platform: this is browser CSS, not cloud | Which system gets the last word |
| Emotion injects inline styles | A per-request nonce on Emotion’s cache (the alternative: hash-based style-src, or unsafe-inline with a recorded exception) | Unchanged on every platform; the nonce is minted in proxy.ts inside your container | How your security office wants styles allowed |
| Default colour scheme | Dark (the alternative: follow the operating system setting) | Unchanged | Which your users need, in writing |
CSS layers
A layer declared later beats a layer declared earlier, whatever the selectors’ specificity. Here is the reference layer order your agent writes at the top of src/app/globals.css, putting MUI in its own layer below Tailwind’s utilities:
@layer theme, base, mui, components, utilities;@import 'tailwindcss';The @layer statement comes first so the order is fixed before Tailwind’s own layers are declared. The cache provider does the other half: enableCssLayer wraps everything Emotion emits for MUI in @layer mui. MUI’s Tailwind guide lists the check for when it does not work: confirm you are on the pinned Tailwind major, and in the browser’s DevTools confirm that mui precedes utilities.
Tailwind has no tailwind.config file in this major: tokens live in an @theme block in the CSS. If your AI tool generates a config file, it is writing for an older major; say so and re-prompt.
Plan the change with your agent
Open your workspace agent at the project root with the project-memory file from Lesson 2 in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and ask:
Read src/proxy.ts and our project-memory file, and plan the application shell so Tailwind utilities override MUI via CSS layers and every Emotion style tag gets a per-request CSP nonce. Ask anything unclear.What to check in the plan before you approve
src/app/globals.cssputs@layer theme, base, mui, components, utilities;on its very first line before@import 'tailwindcss';and defines theme tokens in an@themeblock with notailwind.configfile.src/proxy.tsgenerates a fresh nonce per request on the Node runtime, setsContent-Security-Policywith'nonce-<value>'and no'unsafe-inline'forstyle-src, and forwardsx-nonceon the request headers.src/app/layout.tsxreadsx-noncewithawait headers(), wraps children in<AppRouterCacheProvider options={{ nonce, enableCssLayer: true }}>and the theme provider, and rendersheader,nav, andmainlandmarks.src/components/providers/AppThemeProvider.tsxconfigures the dark MUI palette matching the Tailwind tokens, andAppBarandSidebarprovide the responsive navigation drawers.
If the first plan includes a legacy Tailwind config file or leaves 'unsafe-inline' in style-src, nudge it before approving:
Put the @layer order on line one of globals.css and do not allow unsafe-inline in style-src.What you get
- Typed in the terminal:
claude - Mode:Plan mode
- You type in the session: Read src/proxy.ts and our project-memory file, and plan the application shell so Tailwind utilities override MUI via CSS layers and every Emotion style tag gets a per-request CSP nonce. Ask anything unclear.
- The tool replies: Proposed plan: 1. src/app/globals.css: declare @layer theme, base, mui, components, utilities first, then import tailwindcss and define @theme colour tokens. 2. src/proxy.ts: generate a per-request nonce, set Content-Security-Policy with nonce-based script-src and style-src, and forward x-nonce. 3. src/app/layout.tsx: read x-nonce with await headers() and pass options={{ nonce, enableCssLayer: true }} to AppRouterCacheProvider. 4. src/components/providers/AppThemeProvider.tsx and navigation AppBar/Sidebar with header, nav, and main landmarks. Should style-src forbid unsafe-inline in both development and production?
- You type in the session: Yes, put the @layer order on line one of globals.css and do not allow unsafe-inline in style-src. Build it.
- The tool replies: I created: - src/app/globals.css: layer order first, then the Tailwind import and an @theme block - src/proxy.ts: nonce, CSP header, x-nonce request header, plus the existing cookie redirect - src/app/layout.tsx: async, reads the nonce, wraps children in AppRouterCacheProvider and the theme provider - src/components/providers/AppThemeProvider.tsx - src/components/navigation/AppBar.tsx and Sidebar.tsx One thing to check before you trust it: I passed options={{ nonce, enableCssLayer: true }}. I could not find a nonce option described in MUI's Next.js or CSP pages.
- You type in the session: Then why did you pass it? Show me where you looked.
- The tool replies: Two places in the installed package, not the docs. 1. The type of the options prop is Partial of Emotion's cache options, intersected with an object that adds enableCssLayer. Emotion's cache options include nonce. 2. The provider's source reads options?.nonce when it creates the cache. MUI's own pages say the nonce has to reach Emotion's cache and link to Next's guide, but they do not show this prop. So it works according to the types and the code, not according to MUI's prose. A later release could change that without a documentation note. I would not rely on it without a test that fails when it stops working.
- You type in the session: Write that test. It has to run against a production build, with the real header.
- The tool replies: Created tests/e2e/csp-nonce.spec.ts (Playwright). It loads the home page, reads the nonce out of the response's Content-Security-Policy header, then checks that every style element's nonce property equals it, that at least one Emotion style element exists, and that the console shows no CSP violation. Run it against a production build: next build, then next start, then the test. Dev mode adds directives for hot reload, so it proves less. I also wrote down the negative check: delete nonce from the options and rerun. The test should fail on the first assertion.
- You type in the session: Remove the nonce from the options, rerun, then restore it.
- The tool replies: Without it: 1 failed. Expected style element nonce to equal the header nonce; received an empty string on the Emotion style elements. The console also logged CSP violations. Restored: 1 passed. That is the evidence the test can fail for the right reason.
Illustrative session; exact output varies by tool and agency configuration.
Now read what it wrote.
The nonce, from proxy to style tag
proxy.ts runs before the page renders. It generates the nonce, builds the policy, and does two things with them: it sets the policy on the response, and it forwards the nonce to the app as a request header so the layout can read it. The shape below is Next’s own CSP guide, trimmed to what this lesson tests.
REFERENCE CODE src/proxy.ts: per-request CSP nonce generation and header forwarding open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
// src/proxy.ts (the CSP part; keep the cookie redirect from Lesson 3 above it)import { NextRequest, NextResponse } from "next/server";
export function proxy(request: NextRequest) { const nonce = Buffer.from(crypto.randomUUID()).toString("base64"); const isDev = process.env.NODE_ENV === "development"; const csp = [ "default-src 'self'", `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ""}`, `style-src 'self' 'nonce-${nonce}'`, "img-src 'self' blob: data:", "font-src 'self'", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'none'", ].join("; ");
const requestHeaders = new Headers(request.headers); requestHeaders.set("x-nonce", nonce); requestHeaders.set("Content-Security-Policy", csp);
const response = NextResponse.next({ request: { headers: requestHeaders } }); response.headers.set("Content-Security-Policy", csp); return response;}The layout reads the header with the async form, which is the only form Next accepts now, and hands the value to the cache provider:
REFERENCE CODE src/app/layout.tsx: root layout passing the CSP nonce and CSS layer flag to AppRouterCacheProvider open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { headers } from "next/headers";import { AppRouterCacheProvider } from "@mui/material-nextjs/v16-appRouter";import AppThemeProvider from "@/components/providers/AppThemeProvider";import "./globals.css";
export default async function RootLayout({ children }: { children: React.ReactNode }) { const nonce = (await headers()).get("x-nonce") ?? undefined; return ( <html lang="en"> <body> <AppRouterCacheProvider options={{ nonce, enableCssLayer: true }}> <AppThemeProvider>{children}</AppThemeProvider> </AppRouterCacheProvider> </body> </html> );}Three things to know before you rely on it:
- The import path. MUI’s Next.js page still shows the
v15-appRouterentry. The installed package also shipsv16-appRouter, which re-exports the same provider. Use the one that matches your pinned Next major and check it exists in your installed copy. - Reading
headers()makes every page dynamic. A nonce is per request, so a statically built page cannot carry one. The scaffold fromcreate-next-appmay switch on Cache Components; that feature can raise build errors for request-time data outside aSuspenseboundary. The reference app leaves it off. If your agency turns it on, retest this lesson’s test before you ship. - The nonce prop is documented in types and source, not in MUI’s prose. That is the reason for the test below, not a reason to avoid it.
Browsers hide the value of a nonce attribute once the element is in the page, but the element’s nonce property still returns it. The test reads the property, not the attribute.
Prove it
The test fails if the nonce does not land. It checks the header, then every style element, then the console.
REFERENCE TEST tests/e2e/csp-nonce.spec.ts: Playwright verification that every style tag carries the response nonce open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { test, expect } from "@playwright/test";
test("every style element carries this response's nonce", async ({ page }) => { const violations: string[] = []; page.on("console", (m) => { if (m.text().includes("Content Security Policy")) violations.push(m.text()); });
const response = await page.goto("/"); const csp = response?.headers()["content-security-policy"] ?? ""; const headerNonce = /style-src[^;]*'nonce-([^']+)'/.exec(csp)?.[1]; expect(headerNonce, "style-src names a nonce").toBeTruthy(); expect(csp).not.toMatch(/style-src[^;]*'unsafe-inline'/);
const nonces = await page.$$eval("style", (els) => els.map((e) => (e as HTMLStyleElement).nonce)); expect(nonces.length, "Emotion rendered style elements").toBeGreaterThan(0); for (const n of nonces) expect(n).toBe(headerNonce);
expect(violations).toEqual([]);});
test("two requests get two different nonces", async ({ request }) => { const get = async () => /'nonce-([^']+)'/.exec((await request.get("/")).headers()["content-security-policy"] ?? "")?.[1]; expect(await get()).not.toBe(await get());});Run it against next build and next start, not the dev server. The planted fault is the one the session above used: delete nonce from the provider’s options and the first test must fail. Do that once, on purpose, and record that it failed; a test that has never failed has not shown it can.
Dark mode is an agency decision
The reference app defaults to dark. Its reason is the users: operations staff who work in low-light rooms. That is a reason for that audience, not a rule, and your users may sit in a daylight office.
REFERENCE CODE src/components/providers/AppThemeProvider.tsx: dark-mode MUI theme provider open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
"use client";import { ThemeProvider, createTheme } from "@mui/material/styles";import CssBaseline from "@mui/material/CssBaseline";
const theme = createTheme({ palette: { mode: "dark", // agency decision: record the reason in docs/adr/ background: { default: "#0f172a", paper: "#1e293b" }, primary: { main: "#60a5fa" }, error: { main: "#f87171" }, }, typography: { fontFamily: "var(--font-sans)" },});
export default function AppThemeProvider({ children }: { children: React.ReactNode }) { return ( <ThemeProvider theme={theme}> <CssBaseline /> {children} </ThemeProvider> );}The legitimate alternative is to follow the operating system setting. Whichever you choose, write the decision and its reason in an architecture decision record under docs/adr/ (the layout from Lesson 2), and test the part that does not change: text contrast. WCAG success criterion 1.4.3 asks for at least 4.5 to 1 for normal text, and it applies to both schemes. Lesson 14 covers the full accessibility audit; this check keeps the palette honest in the meantime.
REFERENCE TEST tests/unit/theme-contrast.test.ts: WCAG 1.4.3 palette contrast unit test open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { describe, it, expect } from "vitest";
const lum = (hex: string) => { const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255) .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)); return 0.2126 * r + 0.7152 * g + 0.0722 * b;};const ratio = (a: string, b: string) => { const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x); return (hi + 0.05) / (lo + 0.05);};
describe("theme text contrast", () => { it.each([ ["primary on default background", "#60a5fa", "#0f172a"], ["error on paper", "#f87171", "#1e293b"], ])("%s is at least 4.5 to 1", (_n, fg, bg) => { expect(ratio(fg, bg)).toBeGreaterThanOrEqual(4.5); });});The landmarks
Use header for the app bar, nav for the sidebar, and main for content; screen readers jump between them. MUI’s AppBar renders a header and a Drawer can wrap a nav, but check the generated code for a component="div" override, which silently removes the landmark.
Common failures
| Symptom | Cause | Fix |
|---|---|---|
| A Tailwind class has no effect on a MUI component | mui is declared after utilities, or the @layer line is not first | Check the order in DevTools; confirm enableCssLayer is set |
| Console: “Refused to apply inline style” | The cache provider got no nonce, or the layout read the wrong header name | Run the nonce test; compare the header name in proxy and layout |
| Nonce test passes in dev and fails in production | Dev mode relaxes directives | Run the test against the production build only |
| The page fails to build after enabling Cache Components | Request-time data read outside a Suspense boundary | Wrap the nonce read, or leave the feature off and record that in an ADR |
MUI's pages do not mention a nonce option on AppRouterCacheProvider, but the installed package's types and source accept one. What is the right way to use it?
Your layer order is: theme, base, mui, components, utilities. A MUI button has default padding, and you add a Tailwind padding utility to it. Which wins, and why?
Key takeaway
Declare the layer order first and let enableCssLayer put MUI in its own layer, so the cascade is decided by one line instead of by specificity fights. Generate the nonce in proxy.ts, read it with await headers(), pass it to AppRouterCacheProvider, and say honestly that MUI’s prose does not document that option: then keep a Playwright test that reads the real header and every style element’s nonce, and make sure you have seen it fail once. Dark mode is a recorded decision with a reason, not a default you inherited.
- LEADERSHIP DECISION
- Whether the shell's CSP and nonce test is a release gate, and who records the dark-mode decision.
- PRACTITIONER ACTION
- Run the Playwright nonce test, break the nonce once to watch it fail, then restore it.
- SUCCESS MEASURE
- Audit finding avoided: no inline-style or script violation reaches an assessor that the test did not catch first.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided