- Courses
- 📚Libraries & Frameworks
- 🔺Next.js
- Styling your Next.js application
- Global CSS in Next.js applications
On this page
Next.js CSS – Global Styles, CSS Modules, and External Stylesheets
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Next.js supports multiple CSS strategies out of the box: global CSS for application-wide base styles, CSS Modules for component-scoped styles, Tailwind CSS for utility-first styling, and external stylesheets for third-party libraries. Each serves a different purpose, and choosing the right one for each situation is what keeps a codebase maintainable as it grows. This lesson covers how each mechanism works, where to place files, and how Next.js processes them at build time.
Global CSS
Global CSS applies to every route in the application for its entire lifetime. It is the correct place for CSS resets, base element styles, CSS custom properties (design tokens), and font declarations — styles that are genuinely application-wide and not tied to any single component.
The globals.css file
When you scaffold a Next.js project with create-next-app and select Tailwind CSS, a globals.css file is generated automatically in app/ (or src/app/). This is the file where Tailwind is loaded, and it is also the right place to add your own base styles and custom properties alongside it.
📄 app/globals.css
@import "tailwindcss";
/* CSS custom properties — design tokens available to every component */
:root {
--background: #ffffff;
--foreground: #171717;
--color-primary: #0070f3;
--font-sans: var(--font-geist-sans), system-ui, sans-serif;
--font-mono: var(--font-geist-mono), monospace;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
/* Dark mode base styles */
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
/* Base element styles */
body {
background: var(--background);
color: var(--foreground);
font-family: var(--font-sans);
line-height: 1.6;
}
The @import "tailwindcss" directive loads all of Tailwind's base styles and utilities. The :root block defines CSS custom properties — variables that act as design tokens and are accessible in every component across the application, whether written with Tailwind, CSS Modules, or plain CSS. The @theme inline block registers those tokens with Tailwind v4's theming system.
Importing global CSS in the App Router
In the App Router, globals.css is imported once in the root layout, making every style it defines available to every page and component in the application:
📄 app/layout.tsx
import "./globals.css";
import { Geist, Geist_Mono } from "next/font/google";
import { ReactNode } from "react";
const geistSans = Geist({ subsets: ["latin"], variable: "--font-geist-sans" });
const geistMono = Geist_Mono({
subsets: ["latin"],
variable: "--font-geist-mono",
});
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable}`}>
{children}
</body>
</html>
);
}
The App Router allows global CSS to be imported in any layout, page, or component inside the app directory — but best practice is to do it once, in the root layout. Scattering global imports across multiple files makes ordering unpredictable.
Importing global CSS in the Pages Router
The Pages Router has a strict rule: global CSS files may only be imported inside pages/_app.js or pages/_app.tsx . Importing a global CSS file anywhere else — a page component, a regular component, a nested layout — throws a build error:
Global CSS cannot be imported from files other than your Custom <App>.
See: https://nextjs.org/docs/messages/css-global
This restriction exists because global stylesheets are designed to persist for the lifetime of the application. Allowing imports from arbitrary components would make CSS loading order and persistence impossible to reason about.
📄 pages/_app.tsx
import "../styles/globals.css";
import type { AppProps } from "next/app";
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
If pages/_app.js does not yet exist in the project, create it and restart the development server — Next.js does not hot-reload the first creation of _app.js.
Why global styles persist across routes — the Suspense caveat
Next.js integrates with React's built-in stylesheet support to handle Suspense boundaries correctly. A consequence of this integration is that global stylesheets are not removed from the document as the user navigates between routes. Once a global stylesheet is injected, it stays for the session.
This means that if a global CSS file is imported in a layout that wraps only one section of the app, those styles will still be active when the user navigates elsewhere — potentially conflicting with other components.
The correct practice follows directly from this: restrict global CSS to styles that must genuinely be present everywhere and at all times. Anything component-specific belongs in a CSS Module.
CSS Modules
CSS Modules solve the fundamental problem of plain CSS: class names are global by default. A class named .button in one file conflicts with .button in another. CSS Modules prevent this by automatically generating unique class names at build time, scoping each stylesheet to the component that imports it.
How CSS Modules work
Any file with the .module.css extension is treated as a CSS Module by Next.js — no configuration required. When you import it, you receive a JavaScript object whose keys are the class names you wrote, and whose values are the generated unique identifiers.
📄 app/components/Card/Card.module.css
.card {
background: var(--background);
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 1.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.title {
font-size: 1.25rem;
font-weight: 600;
margin: 0 0 0.5rem;
}
.description {
color: #6b7280;
font-size: 0.875rem;
line-height: 1.5;
}
📄 app/components/Card/Card.tsx
import styles from "./Card.module.css";
type CardProps = {
title: string;
description: string;
};
export default function Card({ title, description }: CardProps) {
return (
<div className={styles.card}>
<h2 className={styles.title}>{title}</h2>
<p className={styles.description}>{description}</p>
</div>
);
}
In the browser, .card becomes something like Card_card__xKj9p — a class name that is unique to this module and cannot conflict with any other stylesheet in the application, regardless of how many other files define a .card class.
CSS Modules are supported in both the App Router and the Pages Router with identical behaviour. Unlike global CSS, they can be imported in any component file with no restrictions on placement.
Combining multiple class names with clsx
When a component needs to apply class names conditionally — based on props, state, or both — string interpolation becomes verbose and error-prone. The clsx library is the standard solution:
npm install clsx
📄 app/components/Button/Button.module.css
.button {
display: inline-flex;
align-items: center;
padding: 0.5rem 1.25rem;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
transition: opacity 0.2s ease;
}
.primary {
background-color: var(--color-primary);
color: #fff;
border: none;
}
.secondary {
background-color: transparent;
color: var(--color-primary);
border: 2px solid var(--color-primary);
}
.disabled {
opacity: 0.5;
cursor: not-allowed;
}
📄 app/components/Button/Button.tsx
import clsx from "clsx";
import styles from "./Button.module.css";
type ButtonProps = {
variant?: "primary" | "secondary";
disabled?: boolean;
children: React.ReactNode;
onClick?: () => void;
};
export default function Button({
variant = "primary",
disabled = false,
children,
onClick,
}: ButtonProps) {
return (
<button
className={clsx(
styles.button,
variant === "primary" && styles.primary,
variant === "secondary" && styles.secondary,
disabled && styles.disabled,
)}
disabled={disabled}
onClick={onClick}
>
{children}
</button>
);
}
clsx accepts any combination of strings, booleans, objects, and arrays, filtering out falsy values automatically. It is small, dependency-free, and far more readable than manual string concatenation for conditional class logic.
Colocating CSS Modules with components
Next.js places no restriction on where .module.css files live in the project. The recommended pattern is to colocate each module with the component it styles:
app/
components/
Button/
Button.tsx
Button.module.css
Card/
Card.tsx
Card.module.css
dashboard/
page.tsx
page.module.css ← scoped styles for this page only
Colocation makes the relationship between a stylesheet and its component explicit and keeps deletion safe — when the component is deleted, its stylesheet goes with it.
External Stylesheets
Third-party CSS published as an npm package — CSS resets, icon fonts, component libraries — can be imported directly in Next.js without any configuration.
In the App Router, external stylesheets can be imported from any layout, page, or component in the app directory. Best practice is to import them in the root layout so they are loaded once and available everywhere:
📄 app/layout.tsx
import "normalize.css";
import "./globals.css";
Install the package first:
npm install normalize.css
Next.js bundles the imported stylesheet into the application's CSS output at build time. Import order matters — see the CSS ordering section below.
In the Pages Router, external CSS packages follow the same restriction as global CSS: they must be imported in pages/_app.js. Importing them in individual page or component files throws a build error.
React 19 note:
<link rel="stylesheet" href="..." />can also be used as a JSX element inside any Server Component. React 19 hoists it to the document<head>automatically, which is an alternative approach for stylesheets needed conditionally on specific routes.
Sass
Next.js has built-in support for Sass — both .scss (SCSS syntax) and .sass (indented syntax). No webpack or PostCSS configuration is required. Install the package and rename files:
npm install --save-dev sass
CSS Modules work with Sass automatically using the .module.scss extension:
/* Button.module.scss */
.button {
padding: 0.5rem 1.25rem;
background-color: var(--color-primary);
border-radius: 4px;
&:hover {
opacity: 0.85;
}
&--secondary {
background-color: transparent;
border: 2px solid var(--color-primary);
}
}
import styles from "./Button.module.scss";
Global Sass files follow the same import rules as global CSS: import them in the root layout (App Router) or pages/_app.js (Pages Router).
CSS Ordering and Production Behaviour
CSS rules that share the same specificity are applied in the order their stylesheets appear in the document. In Next.js, that order is determined by the order files are imported in code.
Consider a page that imports a component before its own module:
// app/dashboard/page.tsx
import Card from "../components/Card/Card"; // imports Card.module.css first
import styles from "./page.module.css"; // imported second
In the generated CSS output, Card.module.css appears before page.module.css, so rules in page.module.css take precedence when specificity is equal. This is predictable as long as import order is consistent across the codebase.
Development vs production
CSS ordering can behave differently between development and production:
- Development (
next dev): CSS updates apply instantly via Fast Refresh. The injection order may differ from production. - Production (
next build): All CSS files are automatically concatenated, minified, and code-split into optimised.cssfiles. Only the CSS needed for a given route is loaded.
Always verify ordering-sensitive styles with next build, not just next dev.
Keeping import order stable
Two practices cause silent CSS ordering bugs and should be avoided:
- Auto-sorting imports with a linter. ESLint's
sort-importsrule and Prettier import-sorting plugins reorder imports alphabetically without understanding CSS dependencies. Disable them for files where import order controls stylesheet precedence. - Importing the same stylesheet from multiple entry points. Extract shared styles into shared components to avoid a stylesheet being imported from different locations with potentially different ordering.
Choosing the Right Strategy
Use caseRecommended approachCSS resets and base element stylesGlobal CSS (globals.css)Design tokens and CSS custom propertiesGlobal CSS (:root block in globals.css)Tailwind utility classes@import "tailwindcss" in globals.cssComponent-specific stylesCSS Modules (.module.css)Page-specific layout stylesCSS Modules colocated with the pageConditional or combined class namesCSS Modules + clsxThird-party CSS librariesExternal stylesheet import in root layoutSass/SCSSInstall sass, rename files to .module.scss
The guiding principle from the official Next.js documentation: use global styles for CSS that is genuinely global and must persist for the lifetime of the application; use CSS Modules for everything component-specific.
Common Mistakes to Avoid
Importing global CSS outside pages/_app.js in the Pages Router. This throws a build error at compile time. Every global CSS import in the Pages Router must live in _app.js.
Using global CSS for component styles. Because global stylesheets are not removed during client-side navigation in the App Router, component-specific styles added to globals.css will persist on every route the user visits after the first load, potentially conflicting with other components.
Treating CSS Module class names as global identifiers. The .button class in a CSS Module is not globally accessible. Do not target it from globals.css or from another module — the generated class name will not match.
Auto-sorting imports with a linter or formatter. Import order directly controls CSS order in Next.js. Alphabetical sorting can silently reorder stylesheets and produce cascading conflicts that are difficult to reproduce and debug.
Not restarting the dev server after creating pages/_app.js for the first time. Next.js does not pick up the addition of _app.js via hot reload. Stop the server with Ctrl+C and restart with npm run dev.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Styling your Next.js application
Next
CSS Modules
-
Global CSS
- The
globals.cssfile - Importing global CSS in the App Router
- Importing global CSS in the Pages Router
- Why global styles persist across routes — the Suspense caveat
- The
-
CSS Modules
- How CSS Modules work
- Combining multiple class names with
clsx - Colocating CSS Modules with components
-
External Stylesheets
-
Sass
-
CSS Ordering and Production Behaviour
- Development vs production
- Keeping import order stable
-
Choosing the Right Strategy
-
Common Mistakes to Avoid
