Unverified Commit 2049354a authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Fix missing styled-jsx styles in Pages Router SSR on adapter builds (#96632)

### What?

Fixes styled-jsx styles being missing from the server-rendered HTML of
Pages
Router apps built through a build adapter (what a Vercel deployment
uses),
when the app has its own `styled-jsx` dependency.

- `crates/next-api/src/next_server_nft.rs`: extracts
`styled_jsx_require_hook_modules()` and adds an accurate comment to the
  `is_using_adapter` early return (it no longer claims no NFT tracing is
  needed - see "Why?").
- `crates/next-api/src/project.rs`: `Project::additional_traced_modules`
now
  also returns those modules, alongside the existing `cacheHandler`/
  `cacheHandlers` entries.
- `packages/next/src/server/require-hook.ts`: extracts
`styledJsxRequireHookEntries()` (the JS-side equivalent, used by
webpack)
and replaces the silent `catch (_) {}` around registering the aliases
with
  a diagnostic warning (still never throws).
- `packages/next/src/build/adapter/build-complete.ts`,
`packages/next/src/build/collect-build-traces.ts`: use that helper
instead
of re-deriving the same resolution inline. No behavior change for
webpack.
- `test/production/adapter-styled-jsx/`: new regression test.

### Why?

The Pages Router renderer and user code have to share a single
`styled-jsx`
module instance: `render.tsx` creates the style registry and hands it to
user code through a React context owned by that specific module
instance. If
user code ends up with a *different* `styled-jsx` instance - which
happens as
soon as the app depends on a `styled-jsx` version that doesn't dedupe
with
Next.js' own pinned version - `JSXStyle` silently renders nothing during
SSR
(`if (!registry) return null`). The `jsx-*` class names are still
emitted by
the transform, so the only visible symptom is a flash of unstyled
content:
the CSS only gets inserted client-side after hydration.

Turbopack keeps `styled-jsx`/`styled-jsx/style` external in the pages
server
bundle, so the single-instance guarantee is established at **runtime**
by
`next/dist/server/require-hook`, which resolves those requests to
Next.js'
own copy from its own install location via a plain `require.resolve()`.
Nothing in any module graph references the files that resolves to (user
code
only ever references its own copy), so output tracing has to add them
explicitly, or the deployment is missing the file, the hook's
`require.resolve()` throws, the aliases are (silently, since #89402)
never
registered, and the two `styled-jsx` instances drift apart.

That explicit tracing existed only for the whole-app
`next-server.js.nft.json` / `next-minimal-server.js.nft.json` - and
those are
not generated at all when a build adapter is used, because an adapter
assembles its output from each endpoint's own NFT instead
(`is_using_adapter` early return in `next_server_nft_assets`). Its
comment
said adapters "don't need any server NFTs" - true for those two
whole-app
files, but not for the styled-jsx entries they also carried, which had
no
other way into an adapter build. Reproduced against a published
`next@16.3.0` release: a plain `next build` with an adapter never
shipped
`node_modules/next/node_modules/styled-jsx/style.js`, nothing deleted or
hand-edited.

### How?

`Project::additional_traced_modules` is Turbopack's existing mechanism
for
"trace this into every endpoint even though nothing references it" - it
already carries `nextConfig.cacheHandler`/`cacheHandlers` for exactly
the
same reason (a runtime-only dependency invisible to static analysis).
Adding the require hook's styled-jsx modules there gets them into every
endpoint's own `*.nft.json` via the existing `trace_endpoint` plumbing,
which
`build-complete.ts` already loads unconditionally for both bundlers - so
no
TypeScript change is needed on the Turbopack side at all.
`styled_jsx_require_hook_modules()` centralizes the resolution (used by
both
`additional_traced_modules` and the pre-existing whole-app NFT, which
still
needs it independently for `output: 'standalone'`).

Webpack has no equivalent Rust-side tracing, so `build-complete.ts`
keeps
tracing these itself via `nodeFileTrace`, now through the shared
`styledJsxRequireHookEntries()` TS helper instead of re-deriving the
same
resolution inline.

The new test builds a Pages Router page with `<style jsx>` through a
build
adapter fixture (same shape as `test/production/adapter-root`), with a
`styled-jsx` dependency version that doesn't dedupe with Next.js' pinned
version, and asserts the adapter's `onBuildComplete` output declares
every
file the require hook resolves.

Verified end-to-end against a published `next@16.3.0` install (the
sandbox
can't build the native Turbopack addon):
- an existing, unmodified mechanism (`cacheHandler`) was used to confirm
the
endpoint-NFT -> adapter-assets pipeline this fix relies on actually
carries
  a traced module through to the deployment;
- the Rust change's exact output was simulated at the point
`build-complete`
  loads each endpoint's NFT, and the SSR HTML went from 0 `<style
id="__jsx-...">` tags (with `jsx-*` classes still present - the reported
  flash) to the expected styled-jsx CSS being present;
- reverting the simulation reproduces the failure again;
- webpack output (`next/node_modules/styled-jsx/{index,style}.js`,
  `node-environment`, `require-hook`) is unaffected.
- `cargo check` / `cargo clippy` / `rustfmt --check` pass on the Rust
change.

- [x] Tests added (`test/production/adapter-styled-jsx/`)
- [x] Errors have a helpful link attached — n/a, no user-facing error
added (warning only)

---------
Co-authored-by: 's avatarvercel-fleet[bot] <308483924+vercel-fleet[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 6ec2ad50
......@@ -2061,6 +2061,7 @@ impl AppEndpoint {
Some(app_function_name(&app_entry.original_name).into()),
*module_graphs.full,
Vc::cell(entry_modules),
this.app_project.project().additional_traced_modules(),
))
}
}
......
......@@ -206,6 +206,7 @@ impl InstrumentationEndpoint {
None,
this.project.module_graph(*userland_module),
Vc::cell(vec![userland_module]),
this.project.additional_traced_modules(),
))
}
}
......
......@@ -345,6 +345,7 @@ impl MiddlewareEndpoint {
None,
this.project.module_graph(*userland_module),
Vc::cell(vec![userland_module]),
this.project.additional_traced_modules(),
))
}
}
......
......@@ -23,6 +23,48 @@ use turbopack_resolve::ecmascript::cjs_resolve;
use crate::{nft::traced_modules_for_entries, project::Project};
/// The modules `next/dist/server/require-hook` resolves its aliased requests to at runtime
/// (currently all of styled-jsx), so that the Pages Router renderer and user code share a single
/// `styled-jsx` module instance (see that file for why they otherwise wouldn't). Nothing in any
/// module graph references these - user code only ever imports its own copy of `styled-jsx` - so
/// whatever assembles a deployment's file list has to include them explicitly, or the hook fails
/// to register its aliases and all styled-jsx styles silently disappear from the server-rendered
/// HTML.
///
/// Used by the server NFTs below and, so that they are part of every endpoint's trace regardless
/// of how the output is assembled, by [`Project::additional_traced_modules`].
#[turbo_tasks::function]
pub(crate) async fn require_hook_modules(project_path: FileSystemPath) -> Result<Vc<Modules>> {
let asset_context = Vc::upcast(externals_tracing_module_context(
get_tracing_compile_time_info(),
false,
));
let next_resolve_origin = Vc::upcast(PlainResolveOrigin::new(
asset_context,
get_next_package(project_path).await?.join("_")?,
));
Ok(Vc::cell(
["styled-jsx", "styled-jsx/style", "styled-jsx/style.js"]
.into_iter()
.map(async |request| {
Ok(cjs_resolve(
next_resolve_origin,
Request::parse_string(request.into()),
CommonJsReferenceSubType::Undefined,
None,
ResolveErrorMode::Error,
)
.await?
.primary_modules()
.await?
.into_iter())
})
.try_flat_join()
.await?,
))
}
#[turbo_tasks::task_input]
#[derive(PartialEq, Eq, TraceRawVcs, Debug, Clone, Hash, Encode, Decode)]
enum ServerNftType {
......@@ -33,8 +75,12 @@ enum ServerNftType {
#[turbo_tasks::function]
pub async fn next_server_nft_assets(project: Vc<Project>) -> Result<Vc<OutputAssets>> {
if *project.next_config().is_using_adapter().await? {
// When using an adapter, we don't need to generate any server NFTs as build-complete
// doesn't use them at all.
// When using an adapter, `next-server.js.nft.json` / `next-minimal-server.js.nft.json` are
// not needed: they exist for `output: 'standalone'` (see `copyTracedFiles`), while an
// adapter assembles the deployment from the per-endpoint NFTs in build-complete.ts. What
// those two files trace on top of the endpoints - the `styled-jsx` modules the require hook
// needs at runtime - is part of every endpoint's trace via
// `Project::additional_traced_modules`, so nothing is lost here.
return Ok(Vc::cell(vec![]));
}
......@@ -218,9 +264,6 @@ impl ServerNftJsonAsset {
get_next_package(project_path.clone()).await?.join("_")?,
));
// These are used by packages/next/src/server/require-hook.ts
let shared_entries = ["styled-jsx", "styled-jsx/style", "styled-jsx/style.js"];
let entries = match self.ty {
ServerNftType::Full => Either::Left(
if is_standalone {
......@@ -242,25 +285,33 @@ impl ServerNftJsonAsset {
)),
};
// The modules the require hook needs are part of every endpoint's trace (see
// `Project::additional_traced_modules`), but `next-server.js` / `next-minimal-server.js`
// are traced on their own for `output: 'standalone'`, so they have to be added here too.
let hook_modules = require_hook_modules(project_path).owned().await?;
Ok(Vc::cell(
shared_entries
hook_modules
.into_iter()
.chain(entries)
.map(async |path| {
Ok(cjs_resolve(
next_resolve_origin,
Request::parse_string(path.into()),
CommonJsReferenceSubType::Undefined,
None,
ResolveErrorMode::Error,
)
.await?
.primary_modules()
.await?
.into_iter())
})
.try_flat_join()
.await?,
.chain(
entries
.map(async |path| {
Ok(cjs_resolve(
next_resolve_origin,
Request::parse_string(path.into()),
CommonJsReferenceSubType::Undefined,
None,
ResolveErrorMode::Error,
)
.await?
.primary_modules()
.await?
.into_iter())
})
.try_flat_join()
.await?,
)
.collect(),
))
}
......
......@@ -56,12 +56,19 @@ impl EndpointTraceResult {
}
}
/// Traces the files an endpoint needs at runtime.
///
/// `traced_entries` are modules that have to be traced even though nothing in `entry_modules`
/// references them, i.e. [`Project::additional_traced_modules`] - or
/// [`Project::pages_traced_modules`] for pages endpoints, which additionally need the modules the
/// require hook resolves at runtime.
#[turbo_tasks::function]
pub async fn trace_endpoint(
project: ResolvedVc<Project>,
page_name: Option<RcStr>,
module_graph: ResolvedVc<ModuleGraph>,
entry_modules: Vc<Modules>,
traced_entries: Vc<Modules>,
) -> Result<Vc<EndpointTraceResult>> {
let span = tracing::info_span!("trace endpoint", path = debug(&page_name));
async {
......@@ -73,8 +80,6 @@ pub async fn trace_endpoint(
.output_file_tracing_includes(project_path.clone())
.await?;
let traced_entries = project.additional_traced_modules();
// Collect referenced assets and externals from module graph
let all_modules = traced_modules_for_entries(
*module_graph,
......
......@@ -1619,6 +1619,9 @@ impl PageEndpoint {
Some(pages_function_name(&this.original_name).into()),
ssr_module_graph,
Vc::cell(vec![ssr_module]),
// The Pages Router renderer resolves `styled-jsx` through the require hook at
// runtime, so those modules have to be traced for pages endpoints.
this.pages_project.project().pages_traced_modules(),
))
}
}
......
......@@ -102,6 +102,7 @@ use crate::{
entrypoints::Entrypoints,
instrumentation::InstrumentationEndpoint,
middleware::MiddlewareEndpoint,
next_server_nft::require_hook_modules,
pages::PagesProject,
route::{
Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups, Endpoints,
......@@ -1452,7 +1453,10 @@ impl Project {
.chain(std::iter::once(self.client_main_modules().owned().await?))
.chain(std::iter::once(GraphEntries::new(
vec![],
self.additional_traced_modules().owned().await?,
// The superset of what any endpoint traces, so that these modules and their
// references are part of the graph. Which endpoint actually traces them is
// decided by what is passed to `trace_endpoint`.
self.pages_traced_modules().owned().await?,
))),
);
......@@ -2841,6 +2845,26 @@ impl Project {
.await?,
))
}
/// [`Project::additional_traced_modules`] plus the modules
/// `next/dist/server/require-hook` resolves at runtime. Only the Pages Router needs the
/// latter, so this is the traced module list for pages endpoints, while other endpoints use
/// [`Project::additional_traced_modules`].
#[turbo_tasks::function]
pub async fn pages_traced_modules(self: Vc<Self>) -> Result<Vc<Modules>> {
let hook_modules = require_hook_modules(self.project_path().owned().await?)
.owned()
.await?;
Ok(Vc::cell(
self.additional_traced_modules()
.owned()
.await?
.into_iter()
.chain(hook_modules)
.collect(),
))
}
}
/// Scales down or shuts down the Node.js process pool after module graph computation.
......
......@@ -2410,7 +2410,7 @@ async function getSharedNodeAssets({
salt
)
// Turbopack handles this automatically and these files are listed in the nft.json files.
// Turbopack traces these itself, they are listed in the nft.json files.
if (bundler !== Bundler.Turbopack) {
const { nodeFileTrace } =
require('next/dist/compiled/@vercel/nft') as typeof import('next/dist/compiled/@vercel/nft')
......@@ -2443,6 +2443,8 @@ async function getSharedNodeAssets({
require.resolve('next/dist/server/node-environment'),
require.resolve('next/dist/server/require-hook'),
require.resolve('next/dist/server/node-polyfill-crypto'),
// Nothing references these, the require hook resolves them at runtime.
// Turbopack traces them via `Project::pages_traced_modules`.
...Object.values(defaultOverrides).filter((item) => path.extname(item)),
]
......
import path from 'path'
import fs from 'fs'
import { createRequire } from 'module'
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
type BuildComplete = Parameters<NextAdapter['onBuildComplete']>[0]
describe('adapter output - styled-jsx', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixture'),
skipStart: true,
// This asserts on the output an adapter is handed locally (`build-complete.json`) and runs the
// app with only the files from that output, so it has to build and serve locally.
skipDeployment: true,
dependencies: {
// A version that does not dedupe with the one Next.js depends on, so the app gets its own
// copy of styled-jsx next to Next.js' copy. That is the case where the require hook in
// next/dist/server/require-hook is load-bearing: without it, user code and the Pages Router
// renderer end up with two styled-jsx instances, the style registry never receives anything
// and every style is silently missing from the server-rendered HTML.
'styled-jsx': '5.1.7',
},
})
if (skipped) return
let buildComplete: BuildComplete
/** Absolute paths of the files the adapter declares for the `/index` pages function. */
let declaredAssets: Set<string>
/** The files the require hook resolves, i.e. what it needs to be able to register its aliases. */
let requireHookFiles: string[]
beforeAll(async () => {
await next.build()
buildComplete = await next.readJSON('build-complete.json')
const indexOutput = buildComplete.outputs.pages.find(
(output) => output.id === '/index'
)
if (!indexOutput) {
throw new Error('missing pages output for /index')
}
declaredAssets = new Set(Object.values(indexOutput.assets))
// Resolve the same way next/dist/server/require-hook does at runtime: the aliases it registers
// (`defaultOverrides`), resolved from Next.js' own location inside the app that was built.
// Note that requiring the hook installs it in this process, which is what Next.js does at
// runtime as well.
const appRequire = createRequire(path.join(next.testDir, 'noop.js'))
const requireHookPath = appRequire.resolve('next/dist/server/require-hook')
const { defaultOverrides } = appRequire(
requireHookPath
) as typeof import('next/dist/server/require-hook')
const hookRequire = createRequire(requireHookPath)
requireHookFiles = [
...new Set(
Object.keys(defaultOverrides).map((request) =>
hookRequire.resolve(request)
)
),
]
})
it('should include the files the require hook resolves in the pages function output', async () => {
// Turbopack traces these via `Project::pages_traced_modules`, webpack via
// `getSharedNodeAssets` in build-complete.ts - either way they have to end up in the
// function's assets, otherwise the require hook can't dedupe styled-jsx at runtime.
expect(requireHookFiles.length).toBeGreaterThan(0)
for (const file of requireHookFiles) {
expect(Array.from(declaredAssets)).toContain(file)
}
})
it('should server render styled-jsx styles with only the declared assets present', async () => {
// Reduce styled-jsx to exactly what the build declared, i.e. what a deployment built from this
// output would contain. If a file the require hook resolves is missing, the hook fails, user
// code and the renderer load two different styled-jsx copies and the styles silently disappear
// from the SSR HTML - while the `jsx-*` class names are still rendered.
function removeUndeclaredFiles(dir: string) {
if (!fs.existsSync(dir)) return
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const entryPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
removeUndeclaredFiles(entryPath)
} else if (!declaredAssets.has(entryPath)) {
fs.rmSync(entryPath)
}
}
}
removeUndeclaredFiles(path.join(next.testDir, 'node_modules/styled-jsx'))
removeUndeclaredFiles(
path.join(next.testDir, 'node_modules/next/node_modules/styled-jsx')
)
await next.start()
const html = await next.render('/')
expect(html).toContain('<style id="__jsx-')
expect(html).toMatch(/color:\s*rebeccapurple/)
})
})
import fs from 'fs'
// @ts-check
/** @type {import('next').NextAdapter } */
const myAdapter = {
name: 'my-styled-jsx-adapter',
onBuildComplete: async (ctx) => {
await fs.promises.writeFile(
'build-complete.json',
JSON.stringify(ctx, null, 2)
)
},
}
export default myAdapter
/** @type {import('next').NextConfig} */
const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'),
outputFileTracingRoot: __dirname,
turbopack: { root: __dirname },
}
module.exports = nextConfig
export default function Page({ color }) {
return (
<div>
<p className="hello">hello styled-jsx</p>
<style jsx>{`
.hello {
color: ${color};
}
`}</style>
</div>
)
}
export function getServerSideProps() {
return { props: { color: 'rebeccapurple' } }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment