Skip to content

Postcss 8.5.24 breaks @layer at rule #2122

Closed

Description

@terrymun

TL;DR: PostCSS 8.5.24 re-adds a BOM after a plugin rebuilds the AST, even though the original input had none. This effectively breaks use of @layer after upgrading from 8.5.23 to 8.5.24. Downgrading to 8.5.23 resolves the issue.

Important

AI use disclaimer: this report was generated with the help of Claude Sonnet 5 after debugging our broken Next.js build after a pnpm dedupe operation bumped postcss from 8.5.23 to 8.5.24.

Original error

When performing a routine pnpm dedupe on our repo (using Next.js + postcss), our Next.js build step started to fail with this following error message:

> Build error occurred
Error: Turbopack build failed with 1 errors:
./packages/castor/src/lib/notification-banner/content/content.module.scss.module.css:1:1
Parsing CSS source code failed
> 1 | @layer bl-design-system {
    | ^
  2 |   .content {
  3 |     grid-area: title;
  4 |     align-self: center;

Unexpected token AtKeyword("layer")

Generated code of PostCSS transform of loaders [next/dist/build/webpack/loaders/resolve-url-loader/index, next/dist/compiled/sass-loader] transform of file content of packages/castor/src/lib/notification-banner/content/content.module.scss:
./packages/castor/src/lib/notification-banner/content/content.module.scss.module.css:1:2
> 1 | @layer bl-design-system{.content{grid-area:title;align-self:center}@media screen and (width >= 640px){.content{grid-area:content}.content .title::after{content:": "}}.collapsibleContainer{grid-area:content;margin-to...
    | ^

Import traces:
  #1 [Client Component Browser]:
    ./packages/castor/src/lib/notification-banner/content/content.module.scss.module.css [Client Component Browser]
    ./packages/castor/src/lib/notification-banner/content/content.module.scss [Client Component Browser]
    ./packages/castor/src/lib/notification-banner/content/content.tsx [Client Component Browser]
    ./packages/castor/src/lib/notification-banner/notification-banner.tsx [Client Component Browser]
    ./packages/castor/src/lib/notification-banner/index.ts [Client Component Browser]
    ./packages/castor/src/index.ts [Client Component Browser]
    ./packages/navigation/src/lib/minimal-header/minimal-header.tsx [Client Component Browser]
    ./apps/portal/app/global-error.tsx [Client Component Browser]
    ./apps/portal/app/global-error.tsx [Server Component]

  #2 [Client Component Browser]:
    ./packages/castor/src/lib/notification-banner/content/content.module.scss.module.css [Client Component Browser]
    ./packages/castor/src/lib/notification-banner/content/content.module.scss [Server Component]
    ./packages/castor/src/lib/notification-banner/content/content.tsx [Server Component]
    ./packages/castor/src/lib/notification-banner/notification-banner.tsx [Server Component]
    ./packages/castor/src/lib/notification-banner/index.ts [Server Component]
    ./packages/castor/src/index.ts [Server Component]
    ./packages/cms-components/src/lib/markdown/markdown.tsx [Server Component]
    ./packages/cms-components/src/lib/markdown/index.ts [Server Component]
    ./packages/cms-components/src/client.ts [Server Component]
    ./apps/portal/app/(minimal-header)/[locale]/child/page.tsx [Server Component]


    at <unknown> (./packages/castor/src/lib/notification-banner/content/content.module.scss.module.css:1:1)
    at <unknown> (./packages/castor/src/lib/notification-banner/content/content.module.scss.module.css:1:2)

By downgrading postcss back to 8.5.23, the build passes without any issue. After performing some investigative work assisted by Claude, I discovered that the BOM re-addition introduced by 8.5.24 is likely the culprit, and in this case it broke the use of @layer in our code, but it is not restricted to the use of this specific CSS at-rule.

Summary

postcss@8.5.24's changelog entry "Preserve the BOM after the processing" changed Stringifier.root() to
unconditionally re-emit a BOM () whenever node.source.input.hasBOM is true — including on the first child
node of the root
, i.e. immediately before whatever the first rule/at-rule in the stylesheet is.

This "preserve" framing only holds when a plugin passes the AST through untouched. As soon as any plugin mutates a node
so the AST is rebuilt (any real-world plugin: autoprefixer, postcss-preset-env, css-loader's postcss-modules, etc.),
postcss 8.5.24 re-inserts the BOM as plain text at the very start of the stringified output — even in cases where
postcss 8.5.23 (and presumably all prior versions) correctly dropped it.

Downstream CSS parsers that don't strip a leading BOM (e.g. Turbopack's lightningcss-based CSS parser) then choke on
the first real token, because it's no longer actually first.

Environment

  • postcss@8.5.23 — correct behavior (BOM dropped)
  • postcss@8.5.24 — regressed behavior (BOM re-inserted)
  • Node.js: v22 (LTS)
  • Reproduced with zero other dependencies — no Sass, no webpack/Turbopack, no autoprefixer required

The relevant diff

lib/stringifier.js, root() method, diff between 8.5.23 → 8.5.24:

   root(node) {
+    if (node.source && node.source.input.hasBOM) {
+      this.builder('', node, 'start')
+    }
     this.body(node)
     if (node.raws.after) this.builder(node.raws.after)
   }

lib/input.js (unchanged between versions) strips a leading BOM from the input string but records the fact on hasBOM:

this.css = css.toString();

if (this.css[0] === '' || this.css[0] === '�') {
  this.hasBOM = true;
  this.css = this.css.slice(1);
} else {
  this.hasBOM = false;
}

So hasBOM is a property of the input, not of the current state of the AST. The new code in 8.5.24 re-adds the BOM
based purely on that input-time flag, regardless of what a plugin did to the tree in between — there's no check for
whether the node being stringified is still, positionally, the original first node of the original input.

Minimal reproduction

No Sass, no bundler — just two isolated installs of postcss and a trivial plugin that mutates a declaration (forcing
the stringifier to actually rebuild output rather than pass the source string through verbatim):

// repro.js — run once against postcss@8.5.23 and once against postcss@8.5.24
const postcss = require('postcss'); // 8.5.23 in one install, 8.5.24 in the other

const input = '@charset "UTF-8";\n.foo { color: red; }';

function mutatePlugin() {
  return {
    postcssPlugin: 'mutate',
    Once(root) {
      root.walkDecls((d) => {
        d.value = d.value.toUpperCase();
      });
    },
  };
}
mutatePlugin.postcss = true;

postcss([mutatePlugin])
  .process(input, { from: undefined })
  .then((result) => {
    console.log(JSON.stringify(result.css));
    console.log('starts with BOM:', result.css.charCodeAt(0) === 0xfeff);
  });

Setup used

mkdir /tmp/pc23 /tmp/pc24
(cd /tmp/pc23 && npm install postcss@8.5.23)
(cd /tmp/pc24 && npm install postcss@8.5.24)

Results

$ node -e "require('/tmp/pc23/node_modules/postcss')..." # (repro.js body, postcss@8.5.23)
"@charset \"UTF-8\";\n.foo { color: RED; }"
starts with BOM: false
$ node -e "require('/tmp/pc24/node_modules/postcss')..." # (repro.js body, postcss@8.5.24)
"@charset \"UTF-8\";\n.foo { color: RED; }"
starts with BOM: true
  • 8.5.23: BOM is correctly dropped — matches pre-8.5.24 behavior across all versions we tested.
  • 8.5.24: BOM is silently re-inserted at the very start of the output, even though the plugin never touched the BOM
    and the AST's first node is a @charset at-rule with no knowledge of any BOM.

Note that without a mutating plugin (postcss([]).process(input)), both versions behave identically (BOM dropped on
parse, absent from output) — the regression only manifests once a plugin causes the tree to actually be
rebuilt/re-stringified, which is the common case for any real-world PostCSS pipeline (autoprefixer, preset-env,
css-loader/postcss-modules, etc.).

Expected behavior

A BOM present in the original source text should either:

  • never be reintroduced once plugins have transformed the tree, or
  • only be reintroduced if it's genuinely still meaningful/intended for the given output (e.g. only for a fully
    pass-through, no-op processing run).

At minimum, "preserving" a BOM should not mean unconditionally injecting a raw  character in front of the first
stringified node whenever the original input happened to have had one, regardless of what happened to the AST
afterward.

Actual real-world impact

We hit this while investigating an Amplify (Next.js 16 / Turbopack) production build failure. A Sass-compiled CSS Module
emits a leading @charset "UTF-8"; (standard Sass behavior for any stylesheet containing non-ASCII content, e.g.
content: ':\a0';), followed by an @layer at-rule as the first real rule:

@charset "UTF-8";
@layer bl-design-system {
  .content { ... }
}

After this passes through our PostCSS pipeline (postcss-import, postcss-flexbugs-fixes, postcss-preset-env, then
css-loader's postcss-modules transform — all of which mutate the AST), postcss 8.5.24 emits a BOM immediately before
the stringified output. Turbopack's CSS parser does not treat a mid-stream BOM as insignificant whitespace, and fails
with:

Unexpected token AtKeyword("layer")

Downgrading/pinning to postcss@8.5.23 (or excluding 8.5.24) resolves the build failure with no other changes
required, which is what led us to isolate the regression to this specific stringifier.js change.

Suggested fix directions

  • Don't reintroduce the BOM at all once any plugin has run Once/OnceExit/mutated the tree — i.e. only preserve it
    for a fully untouched, pass-through root.toResult().
  • Or: track whether the currently first node in the (possibly rearranged/rebuilt) tree still corresponds to the
    original first node/source position before deciding to emit the BOM, rather than keying purely off input.hasBOM.

Activity

  1. ai commented on Jul 29, 2026

    @ai
    Member
  2. vansh2408 commented on Jul 29, 2026

    @vansh2408

    /assign

  3. ai commented on Jul 29, 2026

    @ai
    Member

    @terrymun sorry, LLM output confuses me.

    The "Minimal reproduction" exactly expected code:

    1. The CSS string already has BOM (it is invisible in GitHub, but will be visible if you copy the code)
    2. So starts with BOM: true is happens because PostCSS is keeping BOM (not because it is inserted)

    Seems like your LLM agent do not see BOM marker or was confused. The current PostCSS is expected (PostCSS does not insert BOM on changes, it is only keeping origin BOM).

    Also, I recommend using at least Opus to review issues like this. Sonnet is not capable for complex issues.

  4. ai commented on Jul 29, 2026

    @ai
    Member

    Very likerly the real issue:

    1. You source code files already have BOM markers (please check it)
    2. Some tool after PostCSS is falling because of BOM marker.
    3. Before PostCSS cleaned BOM and helped tool, now PostCSS stopped to hide the next tool bug.

    My recommendation:

    1. Ask LLM for a script to check BOM marker in files and confirm my theory.
    2. Report an issue of not able to process BOM to resolve-url-loader or sass-loader (ask LLM to find where Unexpected token AtKeyword("layer") came from).
    3. Add custom PostCSS plugin which will set root.source.input.hasBOM = false as quick fix until next tool will not be fixed
  5. hdimer commented on Jul 29, 2026

    @hdimer
    Contributor

    Hi @terrymun, thanks for the detailed report, and sorry this broke your build. I opened #2119, so I looked into it.

    The key thing is that your input already contains a BOM, so 8.5.24 is preserving it, not adding one. Running your minimal reproduction plus the negative case (no-BOM input):

    • @charset "UTF-8"; … (BOM in source) → BOM preserved in output
    • @charset "UTF-8"; … (no BOM) → no BOM in output, with or without a mutating plugin

    So a BOM is never introduced, only round-tripped. The leading  is a real U+FEFF in the Sass-generated files. PostCSS ≤ 8.5.23 silently dropped it, which was a byte-fidelity bug: postcss.parse(css).toString() did not equal css. #2119 restored parse(css).toString() === css, and the BOM is always emitted at position 0 (I checked with a node-prepending plugin too).

    The incompatibility is really downstream: per CSS Syntax §3.3 a consumer should strip a leading U+FEFF, and Turbopack's lightningcss parser not doing so is what 8.5.23 was masking.

    Workarounds until then: emit the Sass/source files as UTF-8 without a BOM, or drop a leading BOM before Turbopack sees the CSS (e.g. css.replace(/^/, ''), or a one-line plugin). Happy to help put together a lightningcss repro if it helps file upstream.

  6. ai commented on Jul 29, 2026

    @ai
    Member

    @hdimer thanks for tracking who is falling on BOM parsing.

    Should we create issue in lightningcss? Or does Turbopack use some old version?

  7. terrymun commented on Jul 29, 2026

    @terrymun
    Author

    Hi @hdimer and @ai, thanks for looking into that. I've also mentioned this issue in the Next.js repo: if it is indeed a downstream issue, it is perhaps something they can look into rectifying.

  8. terrymun commented on Jul 29, 2026

    @terrymun
    Author

    @ai Thanks for the tips. I've followed the steps you've recommended and here are my findings:

    1. None of the *.scss or *.css files in the repo contains BOM markers. Since the error message specifically mentions the file content.module.scss, I asked LLM to look at it specifically and it returns with a negative report:

    No BOM anywhere — 634 SCSS and 87 CSS files scanned, zero with a BOM, and content.module.scss starts directly with the @layer bytes (40 6c 61 79 65 72).

    So the BOM exists nowhere on disk in any form. It is created entirely mid-pipeline.

    1. I've asked Claude Opus 5 (not Sonnet 5) to trace the origin of the error message, and it confirms that postcss 8.5.24 simply surfaces the issue: the true bug is for lightningcss or turbopack to fix.

    The error is not from PostCSS, despite what the message framing suggests. Symbol strings in next-swc.darwin-arm64.node place it in turbopack_css::process (turbopack/crates/turbopack-css/src/process.rs), and Unexpected token AtKeyword("layer") is lightningcss's ParserError::UnexpectedToken. The tell in your paste is the column number: 1:2 — the parser is at column 2 while @layer visibly starts at column 1, because an invisible byte occupies column 1.

    The chain

    1. dart-sass compiles content.module.scss. In compressed mode it prepends a UTF-8 BOM whenever the output contains non-ASCII. Here content: ':\a0' decodes to a literal NBSP (C2 A0) — the only such file in the repo.
    2. postcss 8.5.24 re-emits that BOM. This is the regression — stringifier.js gained exactly this, and it's the only functional change between 8.5.23 and 8.5.24 (the other diff is just the version string):
    3. 8.5.23 silently dropped the BOM on stringify; 8.5.24 faithfully preserves it.
    4. lightningcss (inside Turbopack) does not skip a leading BOM, so it tokenizes it as garbage before @layer and throws.
  9. ai commented on Jul 30, 2026

    @ai
    Member

    None of the *.scss or *.css files in the repo contains BOM markers. Since the error message specifically mentions the file content.module.scss, I asked LLM to look at it specifically and it returns with a negative report:

    How did you check BOM? Just asking LLM is not a secure method (since it doesn't have token for BOM)

    You need ask LLM to write a script to check and then manually run this script for files with BOM to be sure that it works.

  10. terrymun commented on Jul 30, 2026

    @terrymun
    Author

    @ai It created a bash script to check for the BOM marker :)

    #!/usr/bin/env bash
    set -euo pipefail
    
    # Checks all SCSS and CSS files for UTF-8 BOM markers (EF BB BF).
    
    found=0
    
    while IFS= read -r file; do
      first_bytes=$(head -c 3 "$file" | od -An -tx1 | tr -d ' \n')
      if [ "$first_bytes" = "efbbbf" ]; then
        echo "BOM found: $file"
        found=1
      fi
    done < <(find . -type d \( -name node_modules -o -name .git -o -name dist -o -name .next \) -prune -o -type f \( -name "*.scss" -o -name "*.css" \) -print)
    
    if [ "$found" -eq 0 ]; then
      echo "No BOM markers found."
    fi
    
    exit "$found"

    I'll close this since it is indeed a turbopack/lightningcss issue.

  11. added 2 commits that reference this issue on Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions