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
- fix(web): inperfect workaround for broken css ordering Disable CSS chunking due to persistent nextjs bug with ordering of css and this seems to help partially. Nextjs in production build only! puts g... — committed to i-am-bee/beeai-platform by Zycon42 2 years ago
- fix(web): css order and add active links (#307) * feat(web): active nav link * fix(web): inperfect workaround for broken css ordering Disable CSS chunking due to persistent nextjs bug with ordering... — committed to i-am-bee/beeai-platform by Zycon42 2 years ago
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.
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!
@Netail No ETA to share yet, but this issue is definitely high on our plate!
Setting
experimental: { cssChunking: 'strict' }innext.config.jsresolves 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.2where 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
falseand'strict'onexperimental.cssChunkingin 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:
@layer reset, theme, ...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:
It does not seem to resolve the issue for us 😦
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/*.cssfiles 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.
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)
@layer global, external;@layer global { ... }node_moduleswith@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
nextjs/postcss.config.js
⚠️ EDIT: I missed this important part. Add the following to your app/layout.tsx in the head tag.
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, andsideEffects: trueshould 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
getModuleReferencesInOrderwithmoduleGraph.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.2fixed this for development but not for prod.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:
layout.tsximports "@/styles/index.scss"- Sets CSS@layersconfigimports ClientComponent from "@/components/client-component"- Removing this component from the RootLayout also fixes the issue, unsure if that’s relevantclient-component"use client"- If we remove this the CSS cascade order gets fixed, interestingly enoughimports PackageComponent from "@repo/ui"- In combination with “use client” causes theuicomponent CSS to get loaded first, breaking CSS@layersSo 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:
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
pages/page-a/index.js
pages/page-b/index.js
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.The solution was to extend the existing cache group config in next.config.js webpack config to put styles in a separate cache group:
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.
I can confirm there are several broken cases with the ordering of CSS, after looking at several <picture data-single-emoji=":repro:" title=":repro:">
</picture>s. We’ve been busy with the 15 release—since that’s out of the way, we will be prioritizing this!
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: falsein 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: falsefrom 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:">
</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.
+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.
@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.tsxfile 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:">
</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:">
</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.
falseresolved 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:">
</picture> <picture data-single-emoji=":docs:" title=":docs:">
</picture>. Thanks for digging deep into that!
@samcx I have it as dependency but with no config file.
@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 version14.2.5and set the flag to “strict”, but unfortunately, the issue persists. I even tried downgrading to version13, but the problem remained, suggesting that it’s not related to changes introduced in version 14 and above.I’m using the
pages routerfor 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:">
</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:">
</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
@importcss 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@importrule 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
@importwas 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
and then import that component in my root layout.js
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:">
</picture>—we will be taking a look at this!