Building an efficient site is critical for both user experience and SEO. Unused CSS is one of the most common problems that can negatively impact website performance. This increases the size of the bundle sent to the client. This article will introduce you to PurgeCSS, a tool that can minimize the CSS sent to the browser.
Sending more CSS than needed not only causes delays and bad experience but also negatively affects theCore Web Vitals, which Google uses 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:
It’s time to learn how to address this problem!
What Is PurgeCSS?
PurgeCSSis 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 sends much more CSS to the client 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 many options.
The tool is available for several technologies and frameworks, including Vue, React, Next.js, Nuxt.js, Hugo, and WordPress. Let’s now look at how to set it up in Next.js!
The following sections will show you how to configure PurgeCSS in Next.js.
Initializing a Next.js App
First, you need a Next.js application. You can initialize one with theNext Create Appcommand below:
npx create-next-app@latest
Follow the procedure and answers all the questions. The default options will do.
√ 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:
npm install bootstrap
Import it by adding the following line on top of thesrc/app/layout.jsfile:
import 'bootstrap/dist/css/bootstrap.css'
If you are not using theNext.js App Routerfeature, add it to thepages/_app.jsfile.
Also, remove theglobals.cssimport. You will not need it anymore.
Update your home page component to use a Bootstrap sample layout, as below:
// src/app/page.js// or if you do not use App Router:// pages/index.jsexport 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:
npm run dev
Visithttp://localhost:3000in the browser, and you should be seeing:
Great! Your Next.js app using Bootstrap as a CSS framework is ready!
Session Replay for Developers
Uncover frustrations, understand bugs and fix slowdowns like never before withOpenReplay— an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.
Check our GitHub repoand join the thousands of developers in our community.
Install PurgeCSS
Next.js relies onPostCSSto produce the bundle stylesheet files. For this reason, the easiest way to configure PurgeCSS is with itsPostCSS plugin. Add it to your project’s dependencies with:
npm install --save-dev @fullhuman/postcss-purgecss
Remember that when you set up a custom PostCSS configuration file, Next.js completelydisables the default behavior. You need to download and configure a couple of plugins to restore that. Install them with the command below:
Recommended by LinkedIn
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 apostcss.config.jsfile in the root folder of your project as follows:
// postcss.config.jsmodule.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, thepostcss-flexbugs-fixesplugin helps to fix various bugs and issues related to Flexbox, ensuring consistent behavior between different browsers.
Then, thepostcss-preset-envplugin converts modern CSS into a format compatible with most browsers. It includesautoprefixer, automatically adding vendor prefixes to CSS properties to support different browser versions. Here, theflexbox: "no-2009"option excludes support for the outdated syntax of the flexbox specification.
Finally,@fullhuman/postcss-purgecssremoves unused CSS from your Next.js app. It involves the following properties:
If your project still uses theNext.js Pages Router, you need to adapt thecontentfield accordingly:
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:
safelist: { standard: ["html", "body"], deep: [ // whitelist all CSS classes that start // with "mt-" and "mb-" /^mt-/, /^mb-/, // whitelist the "highlighted" class "highlighted", ],}
Note that thedeeparray insafeListaccepts both strings and regexes.
When using components from external libraries, you also need to add a special path tocontentas below:
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 inthe official doc.
PurgeCSS in Action
Next.js uses this PostCSS configuration during the build process. This means a change to thepostcss.config.jsfile will not trigger a hot reload. Instead, whenever you update the PostCSS config file, you need to stop the local server, delete the.nextfolder, and relaunchnpm run dev.
To analyze the effects of PurgeCSS, build your Next.js app with:
npm run build
In the.nextfolder, you will find the build bundle. Specifically, the/static/cssfolder will contain the global CSS file generated with PostCSS.
If you open it in Explorer, you will notice its size is 10 KB.
Now, delete thepostcss.config.jsfile and repeat the same procedure. In this case, the CSS files produced by the build operations are two:
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 look at the entire code in theGitHub repository that supports the article. Clone it and launch it with the following:
git clone https://github.com/Tonel/purge-css-next-js-democd purge-css-next-js-demonpm 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!