Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent CSS resolution order with App Router #64921

Open
GabenGar opened this issue Apr 23, 2024 · 84 comments
Open

Inconsistent CSS resolution order with App Router #64921

GabenGar opened this issue Apr 23, 2024 · 84 comments
Labels
CSS Related to CSS. linear: next Confirmed issue that is tracked by the Next.js team.

Comments

@GabenGar
Copy link
Contributor

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

@GabenGar GabenGar added the bug Issue was opened via the bug report template. label Apr 23, 2024
@GabenGar
Copy link
Contributor Author

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

@samcx
Copy link
Member

samcx commented Apr 24, 2024

@GabenGar Thanks for sharing a :repro:—we will be taking a look at this!

@benjitastic
Copy link

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
Copy link
Member

samcx commented May 1, 2024

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

@benjitastic
Copy link

benjitastic commented May 2, 2024

@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.

@github-actions github-actions bot added the linear: next Confirmed issue that is tracked by the Next.js team. label May 13, 2024
@paulyi
Copy link

paulyi commented May 16, 2024

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.

@dstaley
Copy link
Contributor

dstaley commented May 22, 2024

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

@benjitastic
Copy link

benjitastic commented May 22, 2024

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

Interesting -- I can't find any docs anywhere on the cssChunking parameter.

Does anybody know exactly what "strict" css chunking does?

@Netail
Copy link
Contributor

Netail commented May 23, 2024

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 :(

@paulyi

This comment has been minimized.

@samcx
Copy link
Member

samcx commented May 24, 2024

@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 :repro: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!

@Netail
Copy link
Contributor

Netail commented May 24, 2024

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?

@mrabuse
Copy link

mrabuse commented May 28, 2024

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.

@michaelkostal
Copy link

michaelkostal commented May 29, 2024

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).

@samcx
Copy link
Member

samcx commented May 29, 2024

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!

@piratetaco
Copy link

piratetaco commented Jul 2, 2024

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

@samcx
Copy link
Member

samcx commented Jul 8, 2024

@piratetaco Is it possible to :repro: so we can take a closer look?

@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.

@paulyi
Copy link

paulyi commented Jul 8, 2024

@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?

@samcx
Copy link
Member

samcx commented Jul 10, 2024

@paulyi The latest changes should now be in 14.2.5 (includes both fixes mentioned above).

@mrabuse
Copy link

mrabuse commented Jul 10, 2024

@samcx just tried out the 14.2.5 release -- while this release is an improvement, I'm still seeing some incorrect loading of css in the production environment.

@samcx
Copy link
Member

samcx commented Jul 11, 2024

@mrabuse :frog-eyes:

Can you describe exactly how it's loading incorrectly, and is it possible to provide a minimal, public :repro: so we can take a look?

@mrabuse
Copy link

mrabuse commented Jul 11, 2024

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.

@michaelkostal
Copy link

michaelkostal commented Jul 11, 2024

@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!

@samcx
Copy link
Member

samcx commented Jul 12, 2024

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.

@mrabuse :frog-eyes:. Where exactly do you see the order being incorrect (e.g., in a Page that's a Client Component or a Server Component?) Seems like you're doing it all correctly, so a :repro: will be great.

@michaelkostal That's great to hear!

@piratetaco
Copy link

piratetaco commented Jul 12, 2024

sadly I'm unable to get a public repro going. The issue only seems to appear after the components are mixing and matching through the entire component library we're maintaining - but the issue we are seeing is still happening as of 14.2.5.

For now we are going to import higher stylesheets in the component.js in our library as a cumbersome workaround.

import { FirstButton } from '../FirstButton'
// styles that are going out of order
import '../FirstButton.styles.module.scss'
// component styles that should __always__ be added after FirstButton styles based on import order but are not
import styles from './styles.module.scss'

...

@consdu
Copy link

consdu commented Jul 18, 2024

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!

@benjitastic
Copy link

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.

@saltycrane
Copy link

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"

@naimlatifi5
Copy link

naimlatifi5 commented Dec 4, 2024

@samcx any updates on this? Have a similar issue as @saltycrane described above. I tried a different next.js version and upgraded to the latest but the problem persists. This is happening only when running npm run build && npm run start :)

@samcx
Copy link
Member

samcx commented Dec 4, 2024

@naimlatifi5 One fix is still being worked on → #70087

@chaance
Copy link

chaance commented Dec 6, 2024

@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.

@samcx
Copy link
Member

samcx commented Dec 6, 2024

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

@saltycrane
Copy link

saltycrane commented Dec 14, 2024

Probably you already know this, but I found the issue for me was introduced in [email protected]. I decided to roll back to 14.1.4 in our project. Edit: changed my mind about rolling back.

@morriq
Copy link

morriq commented Jan 29, 2025

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;

@samcx samcx added CSS Related to CSS. and removed bug Issue was opened via the bug report template. labels Feb 1, 2025
@wataru-chocola
Copy link

Some people have mentioned that global styles are loaded after individual modules, and this issue might be related to the problem described in the issue below—the CSS order gets messed up when client components are loaded.

#68207

Additionally, I've commented on a potential cause of this problem. Could someone with expertise in webpack processes please take a look?

#68207 (comment)

@studentIvan
Copy link

Solved it by disable the minify classnames plugin and wrote my own, works as magic

@Roman3333
Copy link

#64921 (comment)

Thx, its work. Maybe need it only for dev?
if (!isServer && process.env.NODE_ENV === 'development') {

@samcx samcx changed the title Inconsistent CSS resolution order Inconsistent CSS resolution order with App Router Mar 4, 2025
@mAdutskevich
Copy link

#64921 (comment) doesn't help.
Upgrading to 15.2.1 doesn't help.

Any updates here?

Zycon42 added a commit to i-am-bee/beeai that referenced this issue Mar 7, 2025
Disable CSS chunking due to persistent nextjs bug with ordering of css and this seems to help partially.
Nextjs in production build only! puts global styles last so it messes up css specificity.

We get css modules styles twice but atleast the second css file overwrites them in correct order.

I think it's actually two issues, first is with sideEffects and external packages, because beeai-ui doesn't
have `sideEffects: false` in package.json and I don't wanna add it because it's vite app, not a library
and we have single `index.ts` in it that exports everything, nextjs bundler doesn't tree shake and sees
all styles as required in a root layout. Having separate exports in package.json helps but doesn't mitigrate
the issue completely see second issue bellow.

The second issue is IMHO when the same component is imported from the page and layout and from RSC and from
client component simultaneously, this breaks nextjs and as a result puts global styles after css modules styles.
In our codebase it's a case of a Container component. I wasn't able to refactor this cleanly hence this workaround

vercel/next.js#68207
vercel/next.js#64921
@samcx
Copy link
Member

samcx commented Mar 7, 2025

@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.

@mAdutskevich
Copy link

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

matoushavlena pushed a commit to i-am-bee/beeai that referenced this issue Mar 10, 2025
* feat(web): active nav link

* 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 global styles last so it messes up css specificity.

We get css modules styles twice but atleast the second css file overwrites them in correct order.

I think it's actually two issues, first is with sideEffects and external packages, because beeai-ui doesn't
have `sideEffects: false` in package.json and I don't wanna add it because it's vite app, not a library
and we have single `index.ts` in it that exports everything, nextjs bundler doesn't tree shake and sees
all styles as required in a root layout. Having separate exports in package.json helps but doesn't mitigrate
the issue completely see second issue bellow.

The second issue is IMHO when the same component is imported from the page and layout and from RSC and from
client component simultaneously, this breaks nextjs and as a result puts global styles after css modules styles.
In our codebase it's a case of a Container component. I wasn't able to refactor this cleanly hence this workaround

vercel/next.js#68207
vercel/next.js#64921
@prathamesh-gharat
Copy link

prathamesh-gharat commented Mar 10, 2025

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>

@GlebKodrik

This comment has been minimized.

@GlebKodrik

This comment has been minimized.

@GlebKodrik
Copy link

GlebKodrik commented Mar 17, 2025

@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!

@axten
Copy link

axten commented Mar 20, 2025

I can confirm this. This causes problems for every selector with same weight level.

@consdu
Copy link

consdu commented Mar 20, 2025

@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

@jamie-shawbrook
Copy link

jamie-shawbrook commented Mar 27, 2025

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)
            ` }}/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CSS Related to CSS. linear: next Confirmed issue that is tracked by the Next.js team.
Projects
None yet
Development

No branches or pull requests