Back to overview

Shipping minimal CSS with Next.js + purgeCSS

Minimalistic photo of a gate
| 2 min read
View count:

For a new project I’ll be working on, the company asked to work with Bootstrap to be able to use the built-in grid, utility classes etc. When I think of Bootstrap, I think: a lot of CSS being added to the project which is never used.

With the latest versions of Bootstrap, we have the possibility to only import the SCSS/LESS files for the features we will be using. For example:

@import "~bootstrap/scss/grid";
@import "~bootstrap/scss/tables";
@import "~bootstrap/scss/forms";

The problem with this approach is that these separate files still include a lot of CSS we will not be using in our application.

So what I’d like to do instead, is import the whole bootstrap SCSS, and then delete the unused CSS when building the production output:

@import "~bootstrap/scss/bootstrap";

With this setup, the generated CSS has this size: cssbeforepurge

This is a big CSS chunk for the one class from Bootstrap we’re using:

export default function Home() {
  return (
    <div className="container">

So it would be nice to get rid of this CSS in our production build. To achieve this, we’ll be using purgeCSS.

We just need to add a postcss.config.js file to override the default postCSS config Next.js uses (

Our postcss.config.js will look like this:

module.exports = {
  plugins: [
        autoprefixer: {
          flexbox: "no-2009",
        stage: 3,
        features: {
          "custom-properties": false,
        content: [
        defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
        safelist: ["html", "body"],

Don’t forget to install the node_modules which are used by the postCSS config! (postcss-flexbugs-fixes, @fullhuman/postcss-purgecss, postcss-preset-env, autoprefixer).

When all this is done, you can create a new Next.js build (npm run build) and have the following result: cssafterpurge

Inside the CSS output, it only includes the CSS for the container class, and the CSS variables used by Bootstrap.

That’s a lot of CSS gone! Mission accomplished :-).

Did you like this post? Check out my latest blog posts:

Screenshot of an analytics dashboard
16 Jan 2024

Basic analytics with Vercel Postgres - Drizzle - Astro

10 min reading time

  • vercel
  • databases
  • typescript
  • astro
Page of a dictionary
15 Nov 2023

A minimal dependency-free translation system for Next.js

6 min reading time

  • nextjs
  • react
  • javascript
Chrome logo repeated in a grid
4 Sept 2023

Developing a Chrome extension to convert the current url to localhost in 1 click

4 min reading time

  • javascript
  • chrome extension
  • html