---
# System prepended metadata

title: How To Remove Unused CSS in Next.js With PurgeCSS
tags: [Open Replay]

---

# How To Remove Unused CSS in Next.js With PurgeCSS

Building an efficient site is critical for both user experience and SEO. One of the most common problems that can negatively impact website performance is unused CSS. This increases the size of the bundle sent to the client. Plus, it negatively affects the [Core Web Vitals](https://blog.openreplay.com/complete-guide-googles-core-web-vitals-performance-metrics/), which are used by Google to evaluate the SEO performance of your site. 

At build time, Next.js simply bundles all CSS rules into some optimized files through PostCSS. In other words, it does not automatically remove unused CSS rules. Here is where PurgeCSS comes into play!

Let's learn what PurgeCSS is, how it works, and how to configure it in a Next.js app to make it automatically remove unused CSS rules.

## Why Is Unused CSS a Problem?

Unused CSS occurs when style files sent to the client contain rules that are never used on any page of the site. In a Next.js application, that can cause several issues:

1. **Increased Bundle Size:** Including unused CSS in the frontend application bundle shipped to the client unnecessarily inflates its size. This results in longer loading times and higher bandwidth consumption, affecting both initial rendering and page navigation.
2. **Developer Confusion:** When a codebase contains a lot of extra CSS rules, it becomes more difficult to identify and maintain the styles actually in use. This can cause confusion for developers, leading to errors and inconsistencies. 
3. **Impact on Core Web Vitals:** Google Lighthouse, a tool for measuring a site's Core Web Vitals, [flags unused CSS as a problem](https://developer.chrome.com/en/docs/lighthouse/performance/unused-css-rules/). A low score in those metrics means that Google negatively evaluates the user experience offered by your site, which will result in poor SEO rankings.

It’s time to learn how to address this problem!

## What Is PurgeCSS?

[PurgeCSS](https://purgecss.com/) is a tool for removing unused CSS from a web application. It is based on a simple idea. Most sites rely on CSS frameworks like TailwindCSS, Bootstrap, or MaterializeCSS. However, you typically only use a small subset of such frameworks. This means that your application is sending to the client much more CSS than required.

PurgeCSS matches the CSS selectors used in your HTML elements with those in stylesheets. Then, it automatically removes all unused rules, producing smaller CSS files. Since the default behavior may produce undesired results, it is highly customizable and supports a long list of options. 

The tool is available for several technologies and frameworks, including Vue, React, Next.js, Nuxt.js, Hugo, and WordPress. Let’s now take a look at how to set it up in Next.js!


## Using PurgeCSS to Reduce CSS Bundle Size in Next.js

Follow this step-by-step tutorial and learn how to configure PurgeCSS in Next.js.

### Initializing a Next.js App
First, you need a Next.js application. You can initialize one with the [Next Create App](https://nextjs.org/docs/pages/api-reference/create-next-app) command below:

```bash
npx create-next-app@latest
```
 
Follow the procedure and answers all the questions. The default options will do. 

```bash
√ What is your project named? ... purge-css-next-js-demo
√ Would you like to use TypeScript with this project? ... No / Yes
√ Would you like to use ESLint with this project? ... No / Yes
√ Would you like to use Tailwind CSS with this project? ... No / Yes
√ Would you like to use `src/` directory with this project? ... No / Yes
√ Use App Router (recommended)? ... No / Yes
√ Would you like to customize the default import alias? ... No / Yes
```
 
Next, install Bootstrap. In the project folder, run:

```bash
npm install bootstrap 
```

Import it by adding the following line on top of the `src/app/layout.js` file:

```javascript
import 'bootstrap/dist/css/bootstrap.css'
```

If you are not using the [Next.js App Router](https://nextjs.org/docs/app) feature, add it to the `pages/_app.js` file.

Also, remove the `globals.css` import. You will not need it anymore.

Update your home page component to use a Bootstrap sample layout, as below:

```javascript
// src/app/page.js
// or if you do not use App Router:
// pages/index.js

export default function HomePage() {
  return (
    <div className="container">
      <div className="row">
        <div className="col-md-6">
          <h1>Welcome to My Website</h1>
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod
            vestibulum eros, eu sagittis arcu ullamcorper ut.
          </p>
          <button className="btn btn-primary">Learn More</button>
        </div>
        <div className="col-md-6">
          <div className="card">
            <div className="card-body">
              <h5 className="card-title">Featured Content</h5>
              <p className="card-text">
                Some text describing the featured content.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
```

Verify that everything works as expected by launching the local development server with:

```bash
npm run dev 
```

Visit `http://localhost:3000` in the browser, and you should be seeing:

![](https://i.imgur.com/jJJH3az.png)


Great! Your Next.js app using Bootstrap as a CSS framework is ready!

### Install PurgeCSS
Next.js relies on [PostCSS](https://postcss.org/) to produce the bundle stylesheet files. For this reason, the easiest way to configure PurgeCSS is with its [PostCSS plugin](https://purgecss.com/plugins/postcss.html). Add it to your project's dependencies with:

```bash
npm install --save-dev @fullhuman/postcss-purgecss
```

Keep in mind that when you set up a custom PostCSS configuration file, Next.js completely [disables the default behavior](https://purgecss.com/guides/next.html). To restore that, you need to download and configure a couple of plugins. Install them with the command below:

```bash
npm install postcss-flexbugs-fixes postcss-preset-env
```

Fantastic! You now have everything required to set up PurgeCSS in PostCSS.

### Configure PurgeCSS to Remove Unused CSS
To configure PurgeCSS, create a `postcss.config.js` file in the root folder of your project as follows:

```javascript
// postcss.config.js

module.exports = {
  plugins: [
    // restore the Next.js default behavior
    "postcss-flexbugs-fixes",
    [
      "postcss-preset-env",
      {
        autoprefixer: {
          flexbox: "no-2009",
        },
        stage: 3,
        features: {
          "custom-properties": false,
        },
      },
    ],
    [
      // configure PurgeCSS
      "@fullhuman/postcss-purgecss",
      {
        content: ["./src/app/**/*.{js,jsx,ts,tsx}"],
        defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
        safelist: {
          standard: ["html", "body"],
        },
      },
    ],
  ],
};
```

Let's understand what this configuration file defines by breaking it down into small parts.

First, the [`postcss-flexbugs-fixes`](https://www.npmjs.com/package/postcss-flexbugs-fixes) plugin helps to fix various bugs and issues related to flexbox, ensuring consistent behavior between different browsers.

Then, the [`postcss-preset-env`](https://www.npmjs.com/package/postcss-preset-env) plugin takes care of converting modern CSS into a format compatible with most browsers. It includes [`autoprefixer`](https://github.com/postcss/autoprefixer), which automatically adds vendor prefixes to CSS properties to support different browser versions. Here, the `flexbox: "no-2009"` option excludes support for the outdated syntax of the flexbox specification.

Finally, [`@fullhuman/postcss-purgecss`](https://www.npmjs.com/package/@fullhuman/postcss-purgecss) is responsible for removing unused CSS from your Next.js app. It involves the following properties:

- **`content`**: defines the file paths to be scanned for CSS usage. In this example, it includes all files under the `./src/app` directory and its subdirectories. In particular, PurgeCSS will look for JavaScript, TypeScript, and JSX files and extracts the used CSS selectors from them.
- **`defaultExtractor`**: accepts a function that specifies how PurgeCSS extracts CSS selectors from the content files. It uses a regular expression to match valid selectors and ignores pseudo-elements and pseudo-classes.
- **`safelist`**: specifies a list of selectors that should not be purged even if they are not explicitly used in the `content` files. Usually, you want to exclude the `html` and `body` selectors to ensure they are preserved.

If your project still uses the [Next.js Pages Router](https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts), you need to adapt the `content` field accordingly:

```javascript
 content: [
  './pages/**/*.{js,jsx,ts,tsx}',
  './components/**/*.{js,jsx,ts,tsx}',
]
```

This way, the PurgeCSS plugin will look for CSS selectors in the right folders.

Sometimes, you may need to dynamically add CSS classes on specific events through JavaScript. In this scenario, the CSS selectors are not directly on the HTML elements in the JavaScript files and PurgeCSS will not be able to recognize them as in use. Therefore, it will remove those dynamic classes from the resulting bundle CSS files. To avoid this, you can whitelist CSS classes:

```javascript
safelist: {
  standard: ["html", "body"],
  deep: [
    // whitelist all CSS classes that start
    // with "mt-" and "mb-"
    /^mt-/,
    /^mb-/,
    // whitelist the "highlighted" class
    "highlighted",
  ],
}
```

Note that the `deep` array in `safeList` accepts both strings and regexes.

When using components from external libraries, you also need to add a special path to `content` as below:

```javascript
content: [
  // purging CSS in components from React Bootstrap
  "./node_modules/react-bootstrap/**/*.js",

  // remaining paths...
]
```

Otherwise, PurgeCSS would remove all CSS classes used by library components.

Note that there are many other options and configs available. Explore them in [the official doc](https://purgecss.com/configuration.html).

### PurgeCSS in Action
Next.js uses this PostCSS configuration during the build process. This means that a change to the `postcss.config.js` file will not trigger a hot reload. Instead, every time that you update the PostCSS config file, you need to stop the local server, delete the `.next` folder, and relaunch `npm run dev`.

To analyze the effects of PurgeCSS, build your Next.js app with:

```bash
npm run build
```

In the `.next` folder, you will find the build bundle. Specifically, the `/static/css` folder will contain the global CSS file generated with PostCSS.

![](https://i.imgur.com/jrvo7mt.png)

If you open it in Explorer, you will notice that its size is 10 KB.

Now, delete the `postcss.config.js` file and repeat the same procedure. In this case, the CSS files produced by the build operations are two:

![](https://i.imgur.com/GhJyRa2.png)

The first is the CSS file with the custom rules defined in the application, and the second is the entire Boostrap. Together, their size is 189 KB.

Summing up, PurgeCSS allows you to 179 KB. On such a simple application, that is a huge difference!

You can take a look at the entire code in the [GitHub repository that supports the article](https://github.com/Tonel/purge-css-next-js-demo). Clone it and launch it with:

```bash
git clone https://github.com/Tonel/purge-css-next-js-demo
cd purge-css-next-js-demo
npm run dev
```

Et voilà! You now know how to use PurgeCSS in Next.js to reduce the bundle size and improve the Core Vitals.

## Conclusion

This tutorial is finished! Now you know why unused CSS is a problem for SEO and user experience and how to fix it with PurgeCSS. Here, you saw how to configure PurgeCSS in PostCSS to automatically remove all unused CSS in a Next.js application.

As shown above, removing unnecessary CSS can lead to a significant difference in bundle size. This will result in better download and loading time for the end user!