Fixing CSS load order/style.chunk.css incorrect in Nextjs

Fixing CSS load order/style.chunk.css incorrect in Nextjs

21 May, 2019
Fixing CSS load order/style.chunk.css incorrect in Nextjs


For Nextjs developers, if you are using a third-party UI library for example Material-ui or Semantic-ui, you might end up overriding a lot of the existing styles with your own CSS. That brings to us the importance of the order of which CSS file gets loaded first and after. If your own CSS gets loaded before the Material-ui or Semantic-ui is loaded, all of the work you have done to customize the third-party library's style may be useless, because the CSS that gets loaded after has the higher priority which means you own CSS will do nothing at all!

If you are using Nextjs, you are probably importing you style like this:

In _app.js

import React from 'react';

import 'semantic-ui.css'; import 'myOwnStyle.css';

With this approach is going to work in the development mode as the "semantic-ui.css" is loaded before the "myOwnStyle.css", but unfortunately that's not going to work in production mode after you have typed "npm run build" in your command line. For some reasons, Nextjs will mess up the order and instead load "myOwnStyle.css" first and "semantic-ui.css" after. There have been some issues flying around the Nextjs github repository or the Nextjs space on Spectrum. See some of the related issues. Issue-5121 , and so many more people are having the same issue, and there haven't been a clear fix for it.

Working solution

The solution for this is to put your third-party CSS file into the "static" folder. See the following folder structure:

  • static material-ui.css -pages _document.js

Next, if you don't have document.js in your pages folder, create one that is similar to <a href="">this one that i made</a>. And in the render method, do the following:

render() {
  return (
      <link rel="stylesheet" type="text/css" href="static/material-ui.css" />
        <Main />
        <NextScript />

Voilà, If you deploy your website to production mode now, you can see your own stylings are working again, cheers!

Side note: The above solution is not going to work in Next.js 7 as some fixes for this critical bug are in Nextjs8. So make sure you are using Next.js 8 by typing the following in your command line:

npm i next@latest react@latest react-dom@latest

Interested in learning how to make your own Carousel component that supports multiple items and server-side rendering such as in Nextjs? Check out this post.