# Set up Master CSS in Next.js

Connect Master CSS to the Next.js App Router and verify CSS delivery for pre-rendered and request-time pages.

Add Master CSS to a Next.js App Router project with a top-level `app` directory. Master CSS controls how styles are delivered; Next.js still controls how the page HTML is rendered.

<a id="installation"></a>

## Installation

<a id="add-master-css"></a>

### Add Master CSS

In an existing [Next.js project](https://nextjs.org/docs/app/getting-started/installation), run the installer from the project root. Static is the default: the adapter prepares the generated stylesheet for the Next.js build.

(i) Keep the installer-added `@import '@master/css';` in `app/globals.css`. The adapter processes that entry and supplies generated styles from source scanning.

```bash
npm create @master/css@2.1.8 -- --framework nextjs --yes
```

<a id="verify-the-loaded-configuration"></a>

### Verify the loaded configuration

Keep your global stylesheet imported by the [root layout](https://nextjs.org/docs/app/getting-started/css#global-css), preserving its providers, metadata and document structure. The layout below is a minimal example. When using a TypeScript configuration, return the integration from an async configuration function so an asynchronous build mode does not require top-level await in the config loader:

```ts name=next.config.ts
import type { NextConfig } from 'next'
import withMasterCSS from '@master/css-next'

const nextConfig: NextConfig = {}

export default async () => withMasterCSS(nextConfig, { mode: 'static' })
```

Keep your existing Next.js options in `nextConfig`.

```css name=app/globals.css
@import '@master/css';
```

```tsx name=app/layout.tsx
import './globals.css'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return <html lang="en"><body>{children}</body></html>
}
```

<a id="start-using-master-css"></a>

### Start using Master CSS

Start the dev server and style your first page.

```tsx name=app/page.tsx
export default function Home() {
  return (
    <p id="master-check" className="w-fit m(0) p-md b-solid b(1) b-line-divider r-md text-sm font-regular bg-surface-raised fg-text-strong">
      Hello World
    </p>
  )
}
```

**Using project tokens in CSS Modules**

Local CSS and CSS Modules automatically receive project definitions in both Turbopack and Webpack. Use native declarations with project tokens directly, and native selectors for shared behavior. Their required theme resources are emitted globally, while local selectors retain the framework’s normal scope. Use `@reference` for additional definition files outside the project context.

On the Webpack path, generated theme resources are delivered through an ordinary global stylesheet. Local Module selectors still receive Next.js naming; `:root`, `:host`, and mode selectors keep their original scope. This lets a component inherit tokens from an ancestor or a nested theme without redeclaring them on the component. Repeated components share the generated resources. Native `var(--token)` works in ordinary CSS and CSS Modules with either bundler when the token is supplied by the global entry.

<a id="check-the-setup"></a>

## Check the setup

Run `npm run dev` and change `p-md` to `p-lg` in the page. Padding should grow from `1rem` to `1.5rem`. Restore it, then verify production delivery:

```bash
npm run build
npm run start
```

Disable JavaScript and reload the production page. The paragraph should keep its padding, rounded corners and raised surface. Also check a nested route: importing the global entry from the root layout makes the CSS available across the application.

If styles are missing, check the layout import and that Next.js actually loads the configuration containing `withMasterCSS()`. Keep one active configuration file. For a project using `src/app`, adapt both the stylesheet entry and layout path deliberately; the installer recipe on this page targets top-level `app`.

Enjoying Master CSS? [Star it on GitHub](https://github.com/master-co/css) to help other developers find it.

---

<a id="rendering-modes"></a>

## Choose another rendering mode

Static mode is the default. The installer option sets the matching `withMasterCSS()` mode; keep the global stylesheet when changing modes:

| Mode | Installer option | Delivery |
| --- | --- | --- |
| Static | None | Generated stylesheet from source scanning |
| Prerender | `--mode prerender` | CSS in build-time HTML, with no browser runtime |
| Runtime | `--mode runtime` | Browser runtime through Next.js client instrumentation |
| Progressive | `--mode progressive` | Pre-rendered CSS plus a runtime handoff |

**Generate new classes in the browser**

Runtime mode injects the Master CSS runtime through Next.js client instrumentation without using the build adapter to pre-render page CSS:

```bash
npm create @master/css@2.1.8 -- --framework nextjs --mode runtime --yes
```

The installer sets `withMasterCSS(nextConfig, { mode: 'runtime' })`. Run `npm run build` and `npm run start`, then add a class that was absent from the initial DOM:

```js
document.querySelector('#master-check').classList.add('underline')
```

The paragraph should gain an underline without a rebuild. Runtime mode does not supply those generated rules before JavaScript starts. Check the browser console and runtime program request if the update has no effect.

**Include pre-rendered styles**

Progressive rendering adds pre-rendered CSS and a hydration manifest to static or pre-rendered Next.js pages:

```bash
npm create @master/css@2.1.8 -- --framework nextjs --mode progressive --yes
```

The runtime initially tracks covered classes. A class outside the page manifest starts its engine, which validates and adopts matching rules before generating additional CSS. Request-time dynamic SSR responses are outside the build adapter's pre-rendered output, so their generated utility styles depend on the browser runtime. Use static mode if those routes must have utility styles without JavaScript.

After `npm run build` and `npm run start`, check a pre-rendered route's response source for `style#master-css` before JavaScript runs, then test a later class as above. Test a dynamic SSR route separately: this adapter does not add server-generated CSS to request-time HTML.

Use `--mode prerender` in the same command to deliver CSS with build-time pages and omit the Master CSS browser runtime. Verify `style#master-css` in the built page response. For request-time routes that use complete class names visible in source, choose static mode to deliver those rules.

If a Turbopack production build in runtime or progressive mode reports that a generated `.master/stylesheets/...-entry.css` cannot be resolved, check the Webpack build with `npx next build --webpack` and verify the resulting page with `npm run start` before deployment. A successful Webpack build does not verify the Turbopack path.

<a id="adapter-composition"></a>

## Keep an existing deployment adapter

If the project already uses Next.js [`adapterPath`](https://nextjs.org/docs/app/api-reference/config/next-config-js/adapterPath), keep it in `nextConfig` before passing that configuration to `withMasterCSS()`. The integration composes the configured adapter with its own build adapter. It also recognizes a deployment adapter supplied through `NEXT_ADAPTER_PATH` when no explicit external adapter path is configured.

Master CSS runs first by default. An external adapter that packages the completed HTML can then consume the generated CSS and page manifest references. Use `adapterOrder: 'external-first'` only when the other adapter must process the build outputs first. Change the existing configuration export, retaining the project's options and chosen mode:

```ts
export default async () => withMasterCSS(nextConfig, {
  mode: 'progressive',
  adapterOrder: 'external-first'
})
```

Run the production build with both adapters enabled. Inspect a pre-rendered route in the final deployment output, then its served response: `style#master-css` must survive, and its referenced hydration manifest must load from the deployed URL. Test a dynamic route separately; composing adapters does not add request-time CSS rendering to Master CSS.
