CSS Modules

Learn how Next.js includes CSS modules and some pros and cons.

Selection of styling method in Next.js

Previously, we saw a CSS-in-JS library, meaning that we had to write our CSS definitions in JavaScript, transforming those styling rules to plain CSS at runtime or compile time, depending on which library we choose and how we configure it.

While we personally like the CSS-in-JS approach, we eventually recognized that it has some significant drawbacks to consider when choosing the styling method for a new Next.js app.

Many CSS-in-JS libraries don’t provide good IDE/code editor support, making things way harder for developers (no syntax highlighting, autocomplete, linting, and so on). Also, using CSS-in-JS forces us to adopt more and more dependencies, making our application bundle bigger and slower.

Speaking of performance, here’s another big drawback: even if we pre-generate CSS rules on the server side, we would need to regenerate them after React hydration on the client side. That adds a high runtime cost, making the web application slower and slower, and it will only worsen when we add more features to our app.

But here comes an excellent alternative to Styled JSX: CSS modules. Previously, we talked about locally scoped CSS rules and how Styled JSX makes it easy to create CSS classes with the same names but different purposes (avoiding naming collisions). CSS modules bring the same concept to the table by writing plain CSS classes, then importing them to our React components without any runtime cost.

Let’s look at an elementary example: a simple landing page with a blue background and welcome text. We’ll start with a new Next.js app, then create the pages/index.js file as follows:

Get hands-on with 1200+ tech skills courses.