Generating and inlining critical CSS in Next.js

Your Critical CSS is the part needed to `load above the fold’ content.

When it comes to websites, people really do judge a book by it’s cover.

You need to make sure the first visible part of each of your webpages loads as quickly as possible. Otherwise, people just give up and go somewhere else.

We do that by isolating the CSS which is needed for loading the top part of your page that is immediately visible to users, and pasting it directly into the HTML page itself (inlining).

This is because external stylesheets are treated as a render blocking resource. That means the browser needs to load your external stylesheet(s) before the page can be shown to the user.

Now, you can probably already work out that would be a tedious and complex process.

Thankfully, it can be done automatically by using one small npm dependency and an experimental Next.js feature.

  1. Install Critters npm i -D critters
  2. Add experimental: { optimizeCss: true } to next.config.js

That’s it. I was really surprised at how easy it was to do.

It’s by no means perfect but that’s why it’s labelled experimental and it still delivers a noticable performance benefit.

Share