Reducing CSS bundle size when using Next.js templates

Updated on January 24, 2024

Reducing CSS bundle size when using Next.js templates

I occasionally use Next.js templates when creating websites for clients as more than often than not you can find a template to fit the branding and target audience of the client’s website.

(Although I have to say that there are many more templates available for Gatsby powered sites.. maybe the reason for this is that developers looking to create a fully static site favour Gatsby.js whilst those who need a more hybrid solution including server-side props favour Next.js)

As anyone who has purchased a template before using platforms such as themeforest will know, they are shipped with a large amount of components and pages that you will probably not need - personally I only use around 10% of the components and then I customise the rest according to the clients’ preferences.

The problem that arises after you have removed all the components and pages that you don't need is that you will usually be left with a huge amount of unused CSS which can bloat the bundle size.

Solution

The solution to this issue is extremely straightforward.

I use the PurgeCSS library to remove all the unused CSS in my Next.js projects which could not be easier to integrate.

  1. Firstly install the following packages npm install @fullhuman/postcss-purgecss postcss-flexbugs-fixes postcss-preset-env

  2. Create a postcss.config.js file in the root of the project

  3. Copy the following code into the postcss.config.js file

module.exports = {
    plugins: [
        'postcss-flexbugs-fixes',
        [
            'postcss-preset-env',
            {
                autoprefixer: {
                    flexbox: 'no-2009',
                },
                stage: 3,
                features: {
                    'custom-properties': false,
                },
            },
        ],
        [
            '@fullhuman/postcss-purgecss',
            {
                content: [
                    './pages/**/*.{js,jsx,ts,tsx}',
                    './components/**/*.{js,jsx,ts,tsx}',
                ],
                defaultExtractor: (content) =>
                    content.match(/[\w-/:]+(?<!:)/g) || [],
                safelist: ['html', 'body'],
            },
        ],
    ],
};

Now when you npm run build in your Next.js project you will see vastly reduced.css files in your .next build.

Have a project or idea? Get in touch.

I'm always interested in any opportunity whether that's freelance work, consulting work or employment opportunities. If you have a project that you want to get started, think you need my help with something or just fancy connecting, then please get in touch!

Contact me
Paul McKenna Web Developer Profile Pic
Find me on