Antonello Zanini
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully