next.js: Inconsistent CSS resolution order with App Router

Link to the code that reproduces this issue

https://github.com/GabenGar/repros/blob/main/nextjs/css-out-of-order/README.md

To Reproduce

Reproduction steps are in the README.md

Current vs. Expected behavior

Current: Different CSS resolution order between development and production. Before I had weird client vs. render CSS issues, but it looks like they are fixed in 14.2, although they weren’t super reproducible before either. Expected: Work basically like pages router.

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10
  Available memory (MB): 7990
  Available CPU cores: 4
Binaries:
  Node: 20.9.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.2 // Latest available version is detected (14.2.2).
  eslint-config-next: 14.2.2
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Not sure

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local), next start (local), Vercel (Deployed)

Additional context

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 57
  • Comments: 93 (32 by maintainers)

Commits related to this issue

Most upvoted comments

Dear Next.js team,

I’ve just hit this issue on 14.2.8. It’s frustrating that 14.1.4 still seems to be the last stable ‘golden’ version for reliable CSS ordering. I’ve lost track of how many times I’ve tried upgrading to the latest Next.js. First, it was the environment variable issue, which finally seemed to be resolved, but now it’s this. My project has been stuck on 14.1.4 for over six months, and it’s becoming a blocker. Any updates on when we can expect a real fix?

How is this still a thing? It’s been over a year!

The issue still persist as of 14.2.5 version, I’m using Sass with CSS Modules and I get inconsistent css import order between running the dev server locally and the production build, my app is quite big and I cannot get you a public repo up. Also this doesn’t happen on small projects where only 1 chunk of css is build, in my case I have 5/6 chunks of css being build and I can’t really reproduce something of that magnitude.

Screenshot 2024-07-17 at 18 03 01 Screenshot 2024-07-17 at 18 03 38

In this case its a composed component from an atom where I want to overwrite the gap, locally all works as expected but when building the project the css imported chunks order is being mixed.

My only solution at the moment is the one suggested by @piratetaco but I have a huge project, please fix this!

Do you by any chance have a ETA when development on this will happen?

@Netail No ETA to share yet, but this issue is definitely high on our plate!

Setting experimental: { cssChunking: 'strict' } in next.config.js resolves this issue for us. Not ideal, but better than broken CSS ordering in production!

@samcx I’m experiencing the same issue with Next.js version 15.2.2. The CSS resolution order is inconsistent between development and production, which is causing styling issues in my application. I’ve tried upgrading to the latest version, but the problem persists.

Could the maintainers provide any updates on when this might be fixed? Are there any known workarounds in the meantime?

Thanks!

We are seeing the same issue on 14.2.2 where on production builds the CSS styles get included in an unexpected order.

The specific example we are seeing is that CSS styles imported into layout.js are overriding CSS styles set in a component level stylesheet even though they have the same CSS specificity and the component CSS should override the layout’s CSS. This bug appears to be due to the order that the CSS is included in the final static .css files that are included in the production build.

@samcx Will this fix land in a 14.x patch or only 15? We’re affected by this but still have a bit of work to do to get to Next 15.

I’ve tried both false and 'strict' on experimental.cssChunking in my next.config.ts, and neither seems to do anything. Either way, I get CSS chunked into a single file in the wrong order, and nothing I do seems to change that order.

I’ve tried:

  • Changing the import order in an index CSS file
  • Adding a CSS file to the import that is just a layer order file, e.g. @layer reset, theme, ...
  • Forgoing imports into a CSS file altogether and opting just for stylesheet imports into layout.tsx

Literally the only thing that makes my styles work is if I take all styles, except my reset file, out of CSS layers. Even then, the order the stylesheets are chunked in is still wrong.

This seems like a pretty fundamental problem. If your CSS is out of order, your styles don’t function!

https://github.com/vercel/next.js/issues/64921#issuecomment-2621632945 doesn’t help. Upgrading to 15.2.1 doesn’t help.

Any updates here?

I saw this issue on our project when trying to migrate to App Router and created this minimal repro here: https://github.com/saltycrane/repros/tree/main/next-css-modules-order

When running npm run dev, the button is blue.

But when running npm run build && npm run start, the button is gray.

I don’t understand the cause of the issue. It seemed to be related to which files import which files. If I move components to different files, the results change.

I am using Node.js v22.9.0 on macOS Sonoma and the following npm dependencies:

    "bootstrap": "^5.3.3",
    "next": "^15.0.3",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "reactstrap": "^9.2.3"

Setting experimental: { cssChunking: 'strict' } in next.config.js resolves this issue for us. Not ideal, but better than broken CSS ordering in production!

It does not seem to resolve the issue for us 😦

@benjitastic What kind of CSS styling are you using in this case (e.g., css modules)?

No, not modules. Just like this inside the component:

import './styles.css'


Some more details:

In this case layout.js had this at the top: import '@/styles/customTheme.scss'

And customTheme.scss had this inside it: @import 'bootstrap/scss/bootstrap';

That bootstrap file has a css style declared for .btn like this: .btn { padding: .375rem .75rem }

Then in the component we have an element <button className="btn filter-pill"> and that component includes a styles.css. Inside that styles.css there’s this declaration: .filter-pill { padding: 8px 33px 8px 14px }

The expectation is that .filter-pill padding can override .btn padding. But .btn was overriding .filter-pill styles. This was because of the 5 /_next/static/css/*.css files appearing in the DOM the 1st one contained .filter-pill and the 2nd one contained .btn. This is backwards from expected order. Regardless of it they are in the same static CSS file or not the .btn declaration should come before the .filter-pill declaration.

Hard to post a repro since I think you need a project that has enough CSS to result in multiple static CSS files being generated.

We reverted back to 14.1.4 and the CSS went back to the correct order.

@mAdutskevich @GlebKodrik Creating a specific caching group for styles for production build works for us, note that we didn’t go yet to PROD with this as we are trying to do a regression testing to see if it impacts the app in any other way, we have noticed that this way it creates a bit more css chunks but smaller in size. I think is more a Webpack issue than a Next.js issue, at least for us.

Next 14.2.21 Pages router Styled with Sass and modules

/** @type {import('next').NextConfig} */

const nextConfig = (phase) => ({
 // Your existing config here
  webpack: (config, { isServer }) => {
    // Your existing webpack config here

    if (!isServer) {
      // Create a styles cache group that inherits from default but applies only to CSS
      if (phase === PHASE_PRODUCTION_BUILD) {
        config.optimization.splitChunks.cacheGroups.styles = {
          ...config.optimization.splitChunks.cacheGroups.default,
          test: /\.(css|scss|sass)$/,
          enforce: true,
        };
      }
    }

    return config;
  },
})

module.exports = nextConfig

Created a temporary fix that worked for me. Let me know if you come across any issues along with the error message. I am on NextJS 14.2.24

Edited: Setting layer on CSS that comes from node_modules instead of scss modules now (kept the scss modules as non-layered)

  1. In globals.scss defining the order of layers as @layer global, external;
  2. Wrapping global.scss as @layer global { ... }
  3. Creating a postcss plugin to wrap all CSS that comes from node_modules with @layer external { ... } ( why? - we want the layers to be stacked as non-layered > external > global )

For point 3. nextjs/postcss-plugins/postcss-layer-wrapper.js

const postcss = require('postcss');

module.exports = () => ({
  postcssPlugin: 'postcss-layer-wrapper',
  Once(root, { result }) {
    // Get the file path from the result object
    const filePath = result.opts.from;

    // Only proceed if it's from node_modules
    if (!filePath || !filePath.includes('node_modules')) {
      return;
    }

    const layerRule = postcss.atRule({ name: 'layer', params: 'external' });
    const nodesToMove = [];

    // Collect nodes that can be safely wrapped
    root.each((node) => {
      // Skip @import, @charset, and other non-layerable nodes
      if (node.type === 'atrule' && ['import', 'charset'].includes(node.name))
        return;
      nodesToMove.push(node);
    });

    // Move collected nodes
    nodesToMove.forEach((node) => {
      node.remove();
      layerRule.append(node);
    });

    // Add layer only if it contains nodes
    if (layerRule.nodes && layerRule.nodes.length > 0) {
      root.prepend(layerRule);
    }
  },
});

module.exports.postcss = true;

nextjs/postcss.config.js

module.exports = {
  plugins: [
    // include default Next.js plugins
    'postcss-flexbugs-fixes',
    ['postcss-preset-env', {
      autoprefixer: {
        flexbox: 'no-2009',
      },
      stage: 3,
      features: {
        'custom-properties': false,
      },
    }],

    // custom plugin
    './postcss-plugins/postcss-layer-wrapper.js',

    // cssnano should come last in production
    process.env.NODE_ENV === 'production' ? 'cssnano' : undefined,
  ].filter(Boolean),
};
npm i -d cssnano postcss-flexbugs-fixes postcss-preset-env

⚠️ EDIT: I missed this important part. Add the following to your app/layout.tsx in the head tag.

<style>@layer global, external;</style>

I have isolated at least my issue to this commit released in 14.2.0. If I revert this, css emits in the correct order from a library with or without sideEffects: false set. Looking into why.

I have isolated library css improper order to the changes in this file.

For CSS files, I don’t believe it is a good practice to restrict to only sideEffects: true, like is done in these lines. That forces library authors to sideEffect the entirety of their library including the JS. I think regardless of sideEffects true, false, or set as an array, behavior should always be roughly the same by letting the css compilers handle it, and sideEffects: true should be removed from likely all of these stipulations in this file. Likely responsible for many other existing css issues.

I noticed that if I replace getModuleReferencesInOrder with moduleGraph.getOutgoingConnections(module) my classes are all back in the order I expect (with some minor duplication of different hashes) *that part was a different experiment. This is a major issue in my org preventing further adoption of server components and merging of prs so it hopefully is just a little tweaking to the module reference logic.

I believe this regression was introduced here as part of the 14.2 release.

Edit: It appears that removing the sorting also results in the correct order

It seems 14.2.2 fixed this for development but not for prod.

We got around this using @layer and adding this snippet to the head.

<script dangerouslySetInnerHTML={{ __html: `
              const style = document.createElement('style')
              style.innerHTML = 'LAYER ORDER GOES HERE'
              style.setAttribute('type', 'text/css')
              document.querySelector('head').prepend(style)
            ` }}/>

This incredibly hacky solution solves the problem for our case also, but I kind of refuse to have this in my codebase.

Our case is using Turborepo in a monorepo project. It has been working fine with CSS layers until we implemented this case:

  • app
    • layout.tsx
      • imports "@/styles/index.scss" - Sets CSS @layers config
      • imports ClientComponent from "@/components/client-component" - Removing this component from the RootLayout also fixes the issue, unsure if that’s relevant
    • client-component
      • "use client" - If we remove this the CSS cascade order gets fixed, interestingly enough
      • imports PackageComponent from "@repo/ui" - In combination with “use client” causes the ui component CSS to get loaded first, breaking CSS @layers

So it seems, for our case at least, to be the chunking getting a different order depending on whether it’s a client component importing components or not.

I would love to make a repro but don’t have time currently to set up a whole Turborepo setup to test it out. For now just hope this gives some kind of insight to someone.

@samcx Checked cssChunking true/false/‘strict’, unfortunately doesn’t help.

Until it’s not fixed in nextjs, code below resolves the issue for me:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.optimization.splitChunks = {
        chunks: 'all',
        cacheGroups: {
          styles: {
            name: 'vendor-styles',
            test: /[\\/]node_modules[\\/].*\.(css|scss|sass)$/,
            chunks: 'all',
            enforce: true,
          },
        },
      };
    }
    return config;
  },
};

export default nextConfig;

Encountered this issue in production mode on v14.2.15 using the Pages Router and a custom Webpack 5 config with Mini CSS Extract plugin. The order was fine in development mode.

The issue was due to two pages (A and B) importing and rendering the same Page Template component. The page template imports a Link component and overrides its styles using css modules, while one of the pages (A) also imports the same Link component but does not alter its styling.

PageTemplate.js

import Link from '@atoms/Link'

import styles from './styles.css'

export const PageTemplate = ({children}) => {
    return <div><Link className={styles.overriddenLinkStyles} />{children}</div>
}

pages/page-a/index.js

import Link from '@atoms/Link'
import PageTemplate from '@templates/PageTemplate'

export const PageA = () => {
    return <PageTemplate><Link /></PageTemplate>
}

pages/page-b/index.js

import PageTemplate from '@templates/PageTemplate'

export const PageB = () => {
    return <PageTemplate />
}

The shared Page Template styles were ending up in a separate stylesheet, which was added to the <head> first, followed by the page stylesheet. The stylesheet for page A, as it imports the styles for Link component and does not alter them, overrides the altered Link component styles from Page Template.

<head>
 <link rel="stylesheet" href="__next/static/css/page-template-component-css-here.css" />
 <link rel="stylesheet" href="__next/static/css/pages/page-a-css-overriding-page-template-component-here.css" />
</head>

The solution was to extend the existing cache group config in next.config.js webpack config to put styles in a separate cache group:

// ...

const isCssModule = (module) => {
 return !!module.type?.startsWith('css') || !!module.resource?.endsWith('.css')
}

let originalLibTest
let originalFrameworkTest
let originalLibName

// ....

const optimizationHasBeenOverridden =
     !!config.optimization.splitChunks.cacheGroups?.styles

   if (!optimizationHasBeenOverridden) {
     originalLibTest = config.optimization.splitChunks.cacheGroups?.lib.test

     originalFrameworkTest =
       config.optimization.splitChunks.cacheGroups?.framework.test

     originalLibName = config.optimization.splitChunks.cacheGroups?.lib.name
   }

   config.optimization.splitChunks = {
     ...config.optimization.splitChunks,

     cacheGroups: {
       ...config.optimization.splitChunks.cacheGroups,

       lib: {
         ...config.optimization.splitChunks.cacheGroups?.lib,
         test(module) {
           if (isCssModule(module)) return false

           return originalLibTest(module)
         },
       },

       framework: {
         ...config.optimization.splitChunks.cacheGroups?.framework,
         test(module) {
           if (isCssModule(module)) return false

           return originalFrameworkTest(module)
         },
       },

       styles: {
         name: originalLibName,
         test(module) {
           return isCssModule(module)
         },
         priority: 20,
         minChunks: 1,
         reuseExistingChunk: true,
       },
     },
   }

After the change the stylesheets are added to <head> in the correct order.

Can confirm this issue also comes up in a project using Next.js 14.2., Mantine v7.10 components, and css modules. Works fine in development mode, loads incorrectly in production.

That would be great. We use a design system package and a navigation package which uses the design system package (with some overrides) and the app using the design system, but the overwrites are currently not working on productions. Thus making NextJS kind of unusable currently for us. So the sooner the better 😅

Do you by any chance have a ETA when development on this will happen?

@Netail Thanks for sharing.

Are there any updates on this issue from the nextjs team?

I can confirm there are several broken cases with the ordering of CSS, after looking at several <picture data-single-emoji=":repro:" title=":repro:">:repro:</picture>s. We’ve been busy with the 15 release—since that’s out of the way, we will be prioritizing this!

Does anybody know exactly what “strict” css chunking does?

Getting some answers internally to further clarify this—will respond back soon!

@samcx, My team has built an app-router NextJS app but in order to integrate with a 3rd-party auth SDK we needed to include some pages routes, so we’re technically a hybrid, and therefore we are stuck with both issues simultaneously.

@samcx it is technically possible to use both routers in one Next.js application, so it is possible for a team to be impacted by both issues.

@samcx, your team found a high level security vulnerability around cache-poisoning – you can read the announcement about the problem, the users it impacts, and the fix here. The fix was released on v14.2.10.

The problem for every team impacted by the css rendering order bug is that we cannot upgrade Next.js past v14.1.4 without breaking our production renders. So now we all have to make a choice between staying on v14.1.4 and living with a known security vulnerability until v15 is officially released, or, when @piratetaco’s fix gets merged into the v15 canary, upgrading to the unstable canary version to fix both the css rendering issue and security vulnerability, but having to discover the impacts of the other officially unstable features on our applications. For those reasons, it would be appreciated if when @piratetaco’s fix is approved, you could push for that change to also be backported to v14 quickly.

@Netail I believe he means a v15 release, not 15 PRs.

I have isolated at least my issue and created a replication path! The issue seems to stem from having a library package that is published with sideEffects: false in the package json.

Library and replication path guide:

Simple create next app clone with a page that references library:

Note that if you remove sideEffects: false from the package.json the order is correct and follows the rest of the import order ahead of adding local styles.

@consdu @Robin-Hoodie If you guys can provide a minimal, public <picture data-single-emoji=":repro:" title=":repro:">:repro:</picture>, that will be great!

@samcx I did some additional tests and found that this issue occurs only with components that are deeply nested. I am using the same component, which extends from an atom component, on two different pages. In the first instance, where the styles import correctly, the component is 2 to 3 levels deep in the component tree. In the second instance, where the styles import incorrectly, the component is 7 to 8 levels deep. By levels deep, I mean the page renders a layout component, which renders a container, which renders a section, and so on until the component in question.

I tried manually moving the component higher up in the tree, and this resolved the issue with the incorrect style import. I hope this information is helpful to try find a solution to this problem.

The issue still persist as of 14.2.5 version, I’m using Sass with CSS Modules and I get inconsistent css import order between running the dev server locally and the production build, my app is quite big and I cannot get you a public repo up. Also this doesn’t happen on small projects where only 1 chunk of css is build, in my case I have 5/6 chunks of css being build and I can’t really reproduce something of that magnitude.

Screenshot 2024-07-17 at 18 03 01 Screenshot 2024-07-17 at 18 03 38 In this case its a composed component from an atom where I want to overwrite the gap, locally all works as expected but when building the project the css imported chunks order is being mixed.

My only solution at the moment is the one suggested by @piratetaco but I have a huge project, please fix this!

+1 on this only surfacing once your app generates multiple chunk files. Your explanation of the issue matches exactly the symptoms we reported back in May. I’m still sitting at v14.1.4 and we are waiting to upgrade until this has been resolved, we are not yet considering implementing any work-arounds described in this issue thread as they are cumbersome to implement and maintain.

@michaelkostal Can you try testing a later Next.js version? I believe this :pr: fix (#63157) was not backported to 14.2.2. You can also try the latest canary (greater than v15.0.0-canary.56), which has an additional fix → #67373.

@samcx upgrading to 14.2.5 did resolve my issue. It now appears my global styles are loaded first in order as expected. Thanks!

It’ll take me a bit to build a public repro for you, but I’ll see if I have some time this weekend. The project I’m working on uses Mantine UI for our component library, which has a base styles css file that must be loaded first. Those are imported at the top of our layout.tsx file from the Mantine package (import '@mantine/core/styles.css';). We then use per-file css modules to further style components. In production on 14.2.5, I’m seeing that the imported base styles file gets loaded after all of our css modules, switching the override order.

@piratetaco Is it possible to <picture data-single-emoji=":repro:" title=":repro:">:repro:</picture> so we can take a closer look?

@michaelkostal Can you try testing a later Next.js version? I believe this <picture data-single-emoji=":pr:" title=":pr:">:pr:</picture> fix (https://github.com/vercel/next.js/pull/63157) was not backported to 14.2.2. You can also try the latest canary (greater than v15.0.0-canary.56), which has an additional fix → https://github.com/vercel/next.js/pull/67373.

I am seeing this issue as well, particularly for global styles as well as styles using css modules. As mentioned in this issue, it only happens in production builds.

@mAdutskevich Unfortunately the PR above is still open (the one with sideEffects; the team is aware of it and these issues!).

Curious if cssChunking: false help outs your issue (and for other folks)? I don’t expect it to help for all but gathering data here.

false resolved my issue, where 'strict' did not. I am on 15.1.6, using app router. Let me know if there’s something else I can share about the codebase that would help.

@samcx Is there a solution? I have version 15.2.2 and I have the same problem.

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

@chaance We should be able to backport that PR once it lands!

@naimlatifi5 One fix is still being worked on → https://github.com/vercel/next.js/pull/70087

@piratetaco That’s very interesting—maybe something to add to our <picture data-single-emoji=":nextjs-spin:" title=":nextjs-spin:">:nextjs-spin:</picture> <picture data-single-emoji=":docs:" title=":docs:">:docs:</picture>. Thanks for digging deep into that!

@consdu I see. Just to clarify, the fixes that have been pushed recently all relate to App Router, not Pages Router.

Are you using a postcss.config.js file by any chance? If yes, can you share your config?

@samcx I have it as dependency but with no config file.

@consdu Can you also try using this experimental option (if you haven’t yet)?

experimental: {
  cssChunking: "strict" // default is "loose"
}

x-ref: https://github.com/vercel/next.js/pull/67691/files

@samcx

I did that yes. I’m currently using version 14.1.1, which I believe didn’t include the flag you mentioned. I upgraded to version 14.2.5 and set the flag to “strict”, but unfortunately, the issue persists. I even tried downgrading to version 13, but the problem remained, suggesting that it’s not related to changes introduced in version 14 and above.

I’m using the pages router for my project. I’m happy to provide more screenshots and details about my configuration if needed.

@mrabuse <picture data-single-emoji=":frog-eyes:" title=":frog-eyes:">:frog-eyes:</picture>

Can you describe exactly how it’s loading incorrectly, and is it possible to provide a minimal, public <picture data-single-emoji=":repro:" title=":repro:">:repro:</picture> so we can take a look?

@samcx I face this issue on 14.2.3 as well. Can we backport the additional bug fix to v14 as well for those who cannot switch to a canary version or upgrade a major version at this time?

I had a similar issue, where global styles were bundled after component styles. Running dev I never had an issue, only on production. I’m using Next 14.2.2 with App router and SSG.

My workaround is only for getting global scss that’s imported in layout.js to load ahead of client component scss modules. But perhaps this will be helpful for someone else / debugging the overall issue.

In my root layout.js I was importing /global.scss

There is an @import css rule in there that should be loaded first since that is the first css imported on the page and before any components. However, in dev tools I had the following Issue: An @import rule was ignored because it wasn’t defined at the top.

Indeed there was css rules added above the global.scss.

After analyzing it seems that the css above my @import was all related to client components. This led me to believe that next must prioritize client component styles when bundling css during production builds.

My workaround fix is to make a new client component that imports the styles

"use client";

import "@/scss/global.scss";
const GlobalStyles = () => {
    return <></>;
};

export default GlobalStyles;

and then import that component in my root layout.js

import GlobalStyles from "./GlobalStyles";
export default function RootLayout({ children }) {
    return (
        <html lang="en">
            <GlobalStyles />
            <body>
                {children}
            </body>
        </html>
    );
}

This resolved the issues I was getting in dev tools, and also some issues with specificity (component styles were no longer overriding global styles before the workaround).

@GabenGar Thanks for sharing a <picture data-single-emoji=":repro:" title=":repro:">:repro:</picture>—we will be taking a look at this!