-
Notifications
You must be signed in to change notification settings - Fork 279
fix: RSC compatibility for dynamic() and layout segment context #466
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
Changes from all commits
e409b2f
3532594
54e0793
cf42681
e296edf
e2e1d67
a410275
5bedf20
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,17 +1,23 @@ | ||||||||||||||||||||||||
| "use client"; | ||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||
| * next/dynamic shim | ||||||||||||||||||||||||
| * | ||||||||||||||||||||||||
| * SSR-safe dynamic imports. On the server, uses React.lazy + Suspense so that | ||||||||||||||||||||||||
| * renderToReadableStream suspends until the dynamically-imported component is | ||||||||||||||||||||||||
| * available. On the client, also uses React.lazy for code splitting. | ||||||||||||||||||||||||
| * | ||||||||||||||||||||||||
| * Works in RSC, SSR, and client environments: | ||||||||||||||||||||||||
| * - RSC: Uses React.lazy + Suspense (available in React 19.x react-server). | ||||||||||||||||||||||||
| * Falls back to async component pattern if a future React version | ||||||||||||||||||||||||
| * strips lazy from react-server. | ||||||||||||||||||||||||
| * - SSR: React.lazy + Suspense (renderToReadableStream suspends) | ||||||||||||||||||||||||
| * - Client: React.lazy + Suspense (standard code splitting) | ||||||||||||||||||||||||
| * | ||||||||||||||||||||||||
| * Supports: | ||||||||||||||||||||||||
| * - dynamic(() => import('./Component')) | ||||||||||||||||||||||||
| * - dynamic(() => import('./Component'), { loading: () => <Spinner /> }) | ||||||||||||||||||||||||
| * - dynamic(() => import('./Component'), { ssr: false }) | ||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||
| import React, { lazy, Suspense, type ComponentType, useState, useEffect } from "react"; | ||||||||||||||||||||||||
| import React, { type ComponentType } from "react"; | ||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Clean change. Switching from destructured |
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| interface DynamicOptions { | ||||||||||||||||||||||||
| loading?: ComponentType<{ error?: Error | null; isLoading?: boolean; pastDelay?: boolean }>; | ||||||||||||||||||||||||
|
|
@@ -90,7 +96,7 @@ function dynamic<P extends object = object>( | |||||||||||||||||||||||
| // ssr: false — render nothing on the server, lazy-load on client | ||||||||||||||||||||||||
| if (!ssr) { | ||||||||||||||||||||||||
| if (isServer) { | ||||||||||||||||||||||||
| // On the server, just render the loading state or nothing | ||||||||||||||||||||||||
| // On the server (SSR or RSC), just render the loading state or nothing | ||||||||||||||||||||||||
| const SSRFalse = (_props: P) => { | ||||||||||||||||||||||||
| return LoadingComponent | ||||||||||||||||||||||||
| ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null }) | ||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor concern: when However, if
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Acknowledged — this matches Next.js behavior and the edge case is inherently user error (passing a hook-using component as |
||||||||||||||||||||||||
|
|
@@ -101,15 +107,15 @@ function dynamic<P extends object = object>( | |||||||||||||||||||||||
| } | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| // Client: use lazy with Suspense | ||||||||||||||||||||||||
| const LazyComponent = lazy(async () => { | ||||||||||||||||||||||||
| const LazyComponent = React.lazy(async () => { | ||||||||||||||||||||||||
| const mod = await loader(); | ||||||||||||||||||||||||
| if ("default" in mod) return mod as { default: ComponentType<P> }; | ||||||||||||||||||||||||
| return { default: mod as ComponentType<P> }; | ||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| const ClientSSRFalse = (props: P) => { | ||||||||||||||||||||||||
| const [mounted, setMounted] = useState(false); | ||||||||||||||||||||||||
| useEffect(() => setMounted(true), []); | ||||||||||||||||||||||||
| const [mounted, setMounted] = React.useState(false); | ||||||||||||||||||||||||
| React.useEffect(() => setMounted(true), []); | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| if (!mounted) { | ||||||||||||||||||||||||
| return LoadingComponent | ||||||||||||||||||||||||
|
|
@@ -120,7 +126,11 @@ function dynamic<P extends object = object>( | |||||||||||||||||||||||
| const fallback = LoadingComponent | ||||||||||||||||||||||||
| ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null }) | ||||||||||||||||||||||||
| : null; | ||||||||||||||||||||||||
| return React.createElement(Suspense, { fallback }, React.createElement(LazyComponent, props)); | ||||||||||||||||||||||||
| return React.createElement( | ||||||||||||||||||||||||
| React.Suspense, | ||||||||||||||||||||||||
| { fallback }, | ||||||||||||||||||||||||
| React.createElement(LazyComponent, props), | ||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| ClientSSRFalse.displayName = "DynamicClientSSRFalse"; | ||||||||||||||||||||||||
|
|
@@ -129,12 +139,32 @@ function dynamic<P extends object = object>( | |||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| // SSR-enabled path | ||||||||||||||||||||||||
| if (isServer) { | ||||||||||||||||||||||||
| // Use React.lazy so that renderToReadableStream can suspend until the | ||||||||||||||||||||||||
| // dynamically-imported component is available. The previous eager-load | ||||||||||||||||||||||||
| // pattern relied on flushPreloads() being called before rendering, which | ||||||||||||||||||||||||
| // works for the Pages Router but not the App Router where client modules | ||||||||||||||||||||||||
| // are loaded lazily during RSC stream deserialization (issue #75). | ||||||||||||||||||||||||
| const LazyServer = lazy(async () => { | ||||||||||||||||||||||||
| // Defensive fallback: if a future React version strips React.lazy from the | ||||||||||||||||||||||||
| // react-server condition, fall back to an async component pattern. | ||||||||||||||||||||||||
| // In React 19.x, React.lazy IS available in react-server, so this branch | ||||||||||||||||||||||||
| // does not execute — it exists for forward compatibility only. | ||||||||||||||||||||||||
| if (typeof React.lazy !== "function") { | ||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This guard may not trigger with current React 19.x — This isn't necessarily a problem — the guard is defensive and correct for forward compatibility. But it means:
Could you confirm whether this branch actually executes in the test? A
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The two prior reviews both flagged this and it hasn't been addressed: in React 19.x, This is fine as defensive forward-compat code, but the comment should say so explicitly. The current comment states definitively that
Suggested change
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comments here are now accurate — good job addressing the prior review feedback. The guard, the One nit: the |
||||||||||||||||||||||||
| const AsyncServerDynamic = async (props: P) => { | ||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The Worth a comment noting this is intentional:
Suggested change
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: This async function doesn't have error handling. If
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The previous review flagged that loader rejections in this async path propagate uncaught (no error boundary wrapping). That's acceptable since RSC errors propagate to the nearest error boundary in the component tree. But the
Suggested change
|
||||||||||||||||||||||||
| // Note: LoadingComponent is not used here — in the RSC environment, | ||||||||||||||||||||||||
| // async components suspend natively and parent <Suspense> boundaries | ||||||||||||||||||||||||
| // provide loading states. Error handling also defers to the nearest | ||||||||||||||||||||||||
| // error boundary in the component tree. | ||||||||||||||||||||||||
| const mod = await loader(); | ||||||||||||||||||||||||
| const Component = | ||||||||||||||||||||||||
| "default" in mod | ||||||||||||||||||||||||
| ? (mod as { default: ComponentType<P> }).default | ||||||||||||||||||||||||
| : (mod as ComponentType<P>); | ||||||||||||||||||||||||
| return React.createElement(Component, props); | ||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||
| AsyncServerDynamic.displayName = "DynamicAsyncServer"; | ||||||||||||||||||||||||
| // Cast is safe: async components are natively supported by the RSC renderer, | ||||||||||||||||||||||||
| // but TypeScript's ComponentType<P> doesn't account for async return types. | ||||||||||||||||||||||||
| return AsyncServerDynamic as unknown as ComponentType<P>; | ||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The
Suggested change
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The previous review suggested a comment on this cast. Agree it's worth it — the
Suggested change
|
||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| // SSR path: Use React.lazy so that renderToReadableStream can suspend | ||||||||||||||||||||||||
| // until the dynamically-imported component is available. | ||||||||||||||||||||||||
| const LazyServer = React.lazy(async () => { | ||||||||||||||||||||||||
| const mod = await loader(); | ||||||||||||||||||||||||
| if ("default" in mod) return mod as { default: ComponentType<P> }; | ||||||||||||||||||||||||
| return { default: mod as ComponentType<P> }; | ||||||||||||||||||||||||
|
|
@@ -151,15 +181,15 @@ function dynamic<P extends object = object>( | |||||||||||||||||||||||
| const content = ErrorBoundary | ||||||||||||||||||||||||
| ? React.createElement(ErrorBoundary, { fallback: LoadingComponent }, lazyElement) | ||||||||||||||||||||||||
| : lazyElement; | ||||||||||||||||||||||||
| return React.createElement(Suspense, { fallback }, content); | ||||||||||||||||||||||||
| return React.createElement(React.Suspense, { fallback }, content); | ||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| ServerDynamic.displayName = "DynamicServer"; | ||||||||||||||||||||||||
| return ServerDynamic; | ||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| // Client path: standard React.lazy with Suspense | ||||||||||||||||||||||||
| const LazyComponent = lazy(async () => { | ||||||||||||||||||||||||
| const LazyComponent = React.lazy(async () => { | ||||||||||||||||||||||||
| const mod = await loader(); | ||||||||||||||||||||||||
| if ("default" in mod) return mod as { default: ComponentType<P> }; | ||||||||||||||||||||||||
| return { default: mod as ComponentType<P> }; | ||||||||||||||||||||||||
|
|
@@ -169,7 +199,11 @@ function dynamic<P extends object = object>( | |||||||||||||||||||||||
| const fallback = LoadingComponent | ||||||||||||||||||||||||
| ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null }) | ||||||||||||||||||||||||
| : null; | ||||||||||||||||||||||||
| return React.createElement(Suspense, { fallback }, React.createElement(LazyComponent, props)); | ||||||||||||||||||||||||
| return React.createElement( | ||||||||||||||||||||||||
| React.Suspense, | ||||||||||||||||||||||||
| { fallback }, | ||||||||||||||||||||||||
| React.createElement(LazyComponent, props), | ||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| ClientDynamic.displayName = "DynamicClient"; | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,9 +3,15 @@ | |
| /** | ||
| * Layout segment context provider. | ||
| * | ||
| * This is a "use client" module because it needs React's createContext | ||
| * and useContext, which are NOT available in the react-server condition. | ||
| * The RSC entry renders this as a client component boundary. | ||
| * Must be "use client" so that Vite's RSC bundler renders this component in | ||
| * the SSR/browser environment where React.createContext is available. The RSC | ||
| * entry imports and renders LayoutSegmentProvider directly, but because of the | ||
| * "use client" boundary the actual execution happens on the SSR/client side | ||
| * where the context can be created and consumed by useSelectedLayoutSegment(s). | ||
| * | ||
| * Without "use client", this runs in the RSC environment where | ||
| * React.createContext is undefined, getLayoutSegmentContext() returns null, | ||
| * the provider becomes a no-op, and useSelectedLayoutSegments always returns []. | ||
| * | ||
| * The context is shared with navigation.ts via getLayoutSegmentContext() | ||
| * to avoid creating separate contexts in different modules. | ||
|
Comment on lines
5
to
17
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The updated comment is accurate and well-written. However, the PR description says |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -129,3 +129,75 @@ describe("flushPreloads", () => { | |
| expect(result).toEqual([]); | ||
| }); | ||
| }); | ||
|
|
||
| // ─── RSC async component path ──────────────────────────────────────────── | ||
| // | ||
| // React 19.x exports React.lazy from the react-server condition, so the | ||
| // `typeof React.lazy !== "function"` guard does NOT trigger in current | ||
| // React. The AsyncServerDynamic path is defensive forward-compatibility | ||
| // code for hypothetical future React versions that strip lazy from RSC. | ||
| // | ||
| // We verify it here by temporarily stubbing React.lazy to undefined, | ||
| // simulating the react-server environment of older or stripped React builds. | ||
|
|
||
| describe("next/dynamic RSC async component path (React.lazy unavailable)", () => { | ||
| it("returns an async component (DynamicAsyncServer) when React.lazy is not a function", () => { | ||
| const originalLazy = React.lazy; | ||
| try { | ||
| // @ts-expect-error — simulating react-server condition where lazy is absent | ||
| React.lazy = undefined; | ||
|
|
||
| const DynamicRsc = dynamic(() => Promise.resolve({ default: Hello })); | ||
| expect(DynamicRsc.displayName).toBe("DynamicAsyncServer"); | ||
| } finally { | ||
| React.lazy = originalLazy; | ||
| } | ||
| }); | ||
|
|
||
| it("async component resolves and renders the dynamically loaded component", async () => { | ||
| const originalLazy = React.lazy; | ||
| try { | ||
| // @ts-expect-error — simulating react-server condition where lazy is absent | ||
| React.lazy = undefined; | ||
|
|
||
| const DynamicRsc = dynamic(() => Promise.resolve({ default: Hello })); | ||
| // The returned component is an async function — call it directly as RSC would | ||
| const element = await (DynamicRsc as unknown as (props: object) => Promise<unknown>)({}); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good test. Calling the async component directly and asserting on the returned element type is the right way to verify this path, since RSC renderers invoke async components the same way. |
||
| // Should return a React element rendered from Hello | ||
| expect(element).toBeTruthy(); | ||
| expect((element as React.ReactElement).type).toBe(Hello); | ||
| } finally { | ||
| React.lazy = originalLazy; | ||
| } | ||
| }); | ||
|
|
||
| it("async component handles modules exporting bare component (no default)", async () => { | ||
| const originalLazy = React.lazy; | ||
| try { | ||
| // @ts-expect-error — simulating react-server condition where lazy is absent | ||
| React.lazy = undefined; | ||
|
|
||
| const DynamicRsc = dynamic(() => Promise.resolve(Hello as any)); | ||
| const element = await (DynamicRsc as unknown as (props: object) => Promise<unknown>)({}); | ||
| expect((element as React.ReactElement).type).toBe(Hello); | ||
| } finally { | ||
| React.lazy = originalLazy; | ||
| } | ||
| }); | ||
|
|
||
| it("async component ignores LoadingComponent (defers to parent Suspense boundary)", () => { | ||
| const originalLazy = React.lazy; | ||
| try { | ||
| // @ts-expect-error — simulating react-server condition where lazy is absent | ||
| React.lazy = undefined; | ||
|
|
||
| // LoadingComponent is passed but should be silently ignored in RSC path | ||
| const DynamicRsc = dynamic(() => Promise.resolve({ default: Hello }), { | ||
| loading: LoadingSpinner, | ||
| }); | ||
| expect(DynamicRsc.displayName).toBe("DynamicAsyncServer"); | ||
| } finally { | ||
| React.lazy = originalLazy; | ||
| } | ||
| }); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| // No "use client" — this is a pure React Server Component. | ||
| // Regression test for: https://github.com/cloudflare/vinext/pull/466 | ||
| // | ||
| // In the RSC environment, React.lazy may not be available in future React | ||
| // versions (the react-server condition could strip it). dynamic() has a | ||
| // defensive fallback to an async component pattern for that scenario. | ||
| // In React 19.x, React.lazy IS available in react-server, so this uses | ||
| // the standard LazyServer + Suspense path. | ||
| import dynamic from "next/dynamic"; | ||
|
|
||
| export const NextDynamicRscComponent = dynamic(() => import("../text-dynamic-rsc")); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // No "use client" — this entire page is a React Server Component tree. | ||
| // Regression test for: https://github.com/cloudflare/vinext/pull/466 | ||
| // | ||
| // Verifies that dynamic() works in a pure RSC context. Currently React.lazy | ||
| // is available in react-server, so the standard lazy path handles this. | ||
| // The async fallback path (for future React versions that strip lazy from | ||
| // react-server) is tested in tests/dynamic.test.ts via React.lazy stubbing. | ||
| import { NextDynamicRscComponent } from "../dynamic-imports/dynamic-rsc"; | ||
|
|
||
| export default function RscDynamicPage() { | ||
| return ( | ||
| <div id="rsc-dynamic-content"> | ||
| <NextDynamicRscComponent /> | ||
| </div> | ||
| ); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| // No "use client" — this is a pure React Server Component | ||
| export default function DynamicRsc() { | ||
| return <p id="css-text-dynamic-rsc">next-dynamic dynamic on rsc</p>; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -346,6 +346,28 @@ describe("Next.js compat: app-routes", () => { | |
| } | ||
| }); | ||
|
|
||
| // ── Catch-all dynamic params (Next.js 15 async params) ────── | ||
| // Regression test for: https://github.com/cloudflare/vinext/pull/466 | ||
| // Route handlers must support `await params` (Promise<{ ... }> pattern). | ||
| // Fixture: /api/catch-all/[...slugs]/route.ts uses `await params` | ||
| // | ||
| // Next.js: 'provides params to routes with dynamic parameters' | ||
| // Source: https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/app-routes/app-custom-routes.test.ts#L84-L92 | ||
|
|
||
| it("catch-all route handler supports await params (Next.js 15 async params)", async () => { | ||
| const res = await fetch(`${baseUrl}/api/catch-all/a/b/c`); | ||
| expect(res.status).toBe(200); | ||
| const data = await res.json(); | ||
| expect(data.slugs).toEqual(["a", "b", "c"]); | ||
| }); | ||
|
|
||
| it("catch-all route handler with hyphenated segments", async () => { | ||
| const res = await fetch(`${baseUrl}/api/catch-all/foo-bar/baz-qux`); | ||
| expect(res.status).toBe(200); | ||
| const data = await res.json(); | ||
| expect(data.slugs).toEqual(["foo-bar", "baz-qux"]); | ||
| }); | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch removing this from the "documented skips" list now that the fixture exists. |
||
| // ── Documented skips ───────────────────────────────────────── | ||
| // | ||
| // N/A: 'statically generates correctly with no dynamic usage' | ||
|
|
@@ -379,8 +401,6 @@ describe("Next.js compat: app-routes", () => { | |
| // N/A: 'no response returned' — Tests console error inspection | ||
| // | ||
| // N/A: 'permanentRedirect' — Would need fixture, minor variant of redirect | ||
| // | ||
| // N/A: 'catch-all routes' — Would need fixture with [...slug] route handler | ||
|
|
||
| // ── ISR caching (dev mode) ───────────────────────────────── | ||
| // In dev mode, ISR caching is disabled. Route handlers should NOT emit | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was the only place in the generated entry where
paramswasn't wrapped.makeThenableParams()is already applied to page params (line ~1776), layout params (line ~1903), metadata params, and slot params. Good catch filling the gap.