Unverified Commit 3ed60553 authored by Sam Poder's avatar Sam Poder Committed by GitHub

Revert "[turbopack] Don't SSR on pages only navigated to through a soft nav (#95539)" (#96028)

Causes issues with `use client` it seems.
parent 2a3f8e0c
use anyhow::{Context, Result, bail};
use anyhow::{Context, Result};
use bincode::{Decode, Encode};
use next_core::{
app_structure::{
......@@ -39,8 +39,8 @@ use next_core::{
use tracing::{Instrument, field::Empty};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, FxIndexMap, NonLocalValue, OperationVc, ResolvedVc, TryJoinIterExt, ValueToString,
Vc, fxindexset, trace::TraceRawVcs,
Completion, FxIndexMap, NonLocalValue, ResolvedVc, TryJoinIterExt, ValueToString, Vc,
fxindexset, trace::TraceRawVcs,
};
use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack::{
......@@ -78,8 +78,6 @@ use crate::{
module_graph::{ClientReferencesGraphs, NextDynamicGraphs, ServerActionsGraphs},
nft::{EndpointTraceResult, trace_endpoint},
nft_json::NftJsonAsset,
operation::OptionEndpoint,
output_mode::{OptionSsrMarkTarget, SsrMarkTarget},
paths::{
all_asset_paths, all_paths_in_root, get_asset_paths_from_root, get_js_paths_from_root,
get_wasm_paths_from_root, paths_to_bindings, wasm_paths_to_bindings,
......@@ -1108,49 +1106,9 @@ pub fn app_entry_point_to_route(
.cell()
}
/// Resolves the [`crate::output_mode::OutputModeState`] and page key for an
/// app page HTML endpoint, so that [`crate::output_mode::mark_as_ssr`] can
/// insert the page.
#[turbo_tasks::function(operation, root)]
pub(crate) async fn mark_as_ssr_operation(
endpoint_op: OperationVc<OptionEndpoint>,
) -> Result<Vc<OptionSsrMarkTarget>> {
// Skip marking if the endpoint fails to resolve.
let Some(endpoint) = endpoint_op.connect().await.ok().and_then(|e| *e) else {
return Ok(Vc::cell(None));
};
let Some(app_endpoint) = ResolvedVc::try_downcast_type::<AppEndpoint>(endpoint) else {
bail!("mark_as_ssr is only called for app pages");
};
let app_endpoint = app_endpoint.await?;
if !matches!(
app_endpoint.ty,
AppEndpointType::Page {
ty: AppPageEndpointType::Html,
..
}
) {
bail!("mark_as_ssr is only called for app page HTML endpoints");
}
let Some(state) = *app_endpoint
.app_project
.project()
.output_mode_state()
.await?
else {
bail!("mark_as_ssr is never called outside of a dev session");
};
Ok(Vc::cell(Some(SsrMarkTarget {
state,
page: app_endpoint.page.to_string().into(),
})))
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, TraceRawVcs, NonLocalValue, Encode, Decode)]
enum AppPageEndpointType {
Html,
/// HMR-only: detects Server Component changes but emits no manifests, so it
/// cannot serve a request.
RscHmr,
}
......@@ -1274,38 +1232,26 @@ impl AppEndpoint {
/// All manifests: `Minimal` plus next-font, next-dynamic, ...
Full,
}
let (process_client_assets, process_ssr, emit_manifests, emit_rsc_manifests) = match &this
.ty
{
AppEndpointType::Page { ty, .. } => (
true,
match ty {
AppPageEndpointType::Html => {
match &*project.output_mode_state().await? {
// In development, skip building the Client Component SSR
// chunks until the page has been rendered as a document.
// A page only ever reached through RSC-only soft
// navigations never needs to compile its SSR output.
Some(state) => *state.is_ssr_page(this.page.to_string().into()).await?,
None => true,
}
}
AppPageEndpointType::RscHmr => false,
},
match ty {
AppPageEndpointType::Html => EmitManifests::Full,
AppPageEndpointType::RscHmr => EmitManifests::None,
},
matches!(ty, AppPageEndpointType::Html),
),
AppEndpointType::Route { .. } => (false, false, EmitManifests::Minimal, true),
AppEndpointType::Metadata { metadata } => (
false,
false,
EmitManifests::Minimal,
matches!(metadata, MetadataItem::Dynamic { .. }),
),
};
let (process_client_assets, process_ssr, emit_manifests, emit_rsc_manifests) =
match &this.ty {
AppEndpointType::Page { ty, .. } => (
true,
matches!(ty, AppPageEndpointType::Html),
if matches!(ty, AppPageEndpointType::Html) {
EmitManifests::Full
} else {
EmitManifests::None
},
matches!(ty, AppPageEndpointType::Html),
),
AppEndpointType::Route { .. } => (false, false, EmitManifests::Minimal, true),
AppEndpointType::Metadata { metadata } => (
false,
false,
EmitManifests::Minimal,
matches!(metadata, MetadataItem::Dynamic { .. }),
),
};
let node_root = project.node_root().owned().await?;
let client_relative_path = project.client_relative_path().owned().await?;
......@@ -1334,7 +1280,7 @@ impl AppEndpoint {
let client_chunking_context = project.client_chunking_context().to_resolved().await?;
let server_chunking_context = if process_ssr || is_app_page {
let ssr_chunking_context = if process_ssr {
Some(
match runtime {
NextRuntime::NodeJs => Vc::upcast(project.server_chunking_context(true)),
......@@ -1350,12 +1296,6 @@ impl AppEndpoint {
None
};
let ssr_chunking_context = if process_ssr {
server_chunking_context
} else {
None
};
let per_page_module_graph = *project.per_page_module_graph().await?;
let next_dynamic_imports =
......@@ -1608,13 +1548,6 @@ impl AppEndpoint {
client_references_chunks,
client_chunking_context,
ssr_chunking_context,
// Only pages need `rscModuleMapping`; route handlers and
// metadata routes keep emitting no module mappings.
rsc_chunking_context: if is_app_page {
server_chunking_context
} else {
None
},
async_module_info: module_graphs.full.async_module_info().to_resolved().await?,
next_config: project.next_config().to_resolved().await?,
runtime,
......
......@@ -18,7 +18,6 @@ pub mod next_server_nft;
mod nft;
mod nft_json;
pub mod operation;
pub mod output_mode;
mod pages;
pub mod paths;
pub mod project;
......
use anyhow::Result;
use bincode::{Decode, Encode};
use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr;
use turbo_tasks::{
NonLocalValue, OperationVc, ResolvedVc, State, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
};
use crate::{app::mark_as_ssr_operation, operation::OptionEndpoint};
#[turbo_tasks::value]
pub struct OutputModeState {
/// App pages that must emit full HTML output, including Client Component
/// SSR chunks. Insert-only: once a page has been rendered as a document it
/// never downgrades to the SSR-free output.
ssr_pages: State<FxHashSet<RcStr>>,
}
impl OutputModeState {
/// This must not be a `#[turbo_tasks::function]` because it should be a
/// singleton for each project.
pub fn new() -> ResolvedVc<Self> {
OutputModeState {
ssr_pages: State::new(FxHashSet::default()),
}
.resolved_cell()
}
fn mark_ssr(&self, page: RcStr) {
self.ssr_pages
.update_conditionally(|pages| pages.insert(page));
}
}
#[turbo_tasks::value_impl]
impl OutputModeState {
#[turbo_tasks::function]
pub fn is_ssr_page(&self, page: RcStr) -> Vc<bool> {
Vc::cell(self.ssr_pages.get().contains(&page))
}
}
#[turbo_tasks::value(transparent)]
pub struct OptionOutputModeState(Option<ResolvedVc<OutputModeState>>);
#[derive(
TraceRawVcs, PartialEq, Eq, ValueDebugFormat, Clone, Debug, NonLocalValue, Encode, Decode,
)]
pub struct SsrMarkTarget {
pub state: ResolvedVc<OutputModeState>,
pub page: RcStr,
}
#[turbo_tasks::value(transparent)]
pub struct OptionSsrMarkTarget(Option<SsrMarkTarget>);
/// Marks the app page served by `endpoint_op` as requiring full HTML output
/// from now on. No-op for endpoints other than app page HTML endpoints.
pub async fn mark_as_ssr(endpoint_op: OperationVc<OptionEndpoint>) -> Result<()> {
let target = mark_as_ssr_operation(endpoint_op)
.read_strongly_consistent()
.await?;
if let Some(target) = &*target {
target.state.await?.mark_ssr(target.page.clone());
}
Ok(())
}
......@@ -99,7 +99,6 @@ use crate::{
entrypoints::Entrypoints,
instrumentation::InstrumentationEndpoint,
middleware::MiddlewareEndpoint,
output_mode::{OptionOutputModeState, OutputModeState},
pages::PagesProject,
route::{
Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups, Endpoints,
......@@ -467,7 +466,6 @@ pub struct ProjectContainer {
name: RcStr,
options_state: State<Option<ProjectOptions>>,
versioned_content_map: Option<ResolvedVc<VersionedContentMap>>,
output_mode_state: Option<ResolvedVc<OutputModeState>>,
}
#[turbo_tasks::value_impl]
......@@ -483,13 +481,6 @@ impl ProjectContainer {
} else {
None
},
// only dev serves pages on demand, so only dev can defer the
// Client Component SSR output of a page
output_mode_state: if dev {
Some(OutputModeState::new())
} else {
None
},
options_state: State::new(None),
}
.cell())
......@@ -875,7 +866,6 @@ impl ProjectContainer {
NextMode::Build.resolved_cell()
},
versioned_content_map: self.versioned_content_map,
output_mode_state: self.output_mode_state,
build_id,
encryption_key,
preview_props,
......@@ -961,11 +951,6 @@ pub struct Project {
versioned_content_map: Option<ResolvedVc<VersionedContentMap>>,
/// Tracks which app pages must emit full HTML output in development. Like
/// [`Project::versioned_content_map`], this is the same cell across
/// `Project` re-creations, so the state survives options changes.
output_mode_state: Option<ResolvedVc<OutputModeState>>,
build_id: RcStr,
encryption_key: RcStr,
......@@ -1072,11 +1057,6 @@ impl Project {
PagesProject::new(self)
}
#[turbo_tasks::function]
pub fn output_mode_state(&self) -> Vc<OptionOutputModeState> {
Vc::cell(self.output_mode_state)
}
#[turbo_tasks::function]
pub fn project_fs(&self) -> Result<Vc<DiskFileSystem>> {
let denied_path = match join_path(&self.project_path, &self.dist_dir_root) {
......
......@@ -117,7 +117,6 @@ pub struct ClientReferenceManifest {
pub client_references_chunks: ResolvedVc<ClientReferencesChunks>,
pub client_chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
pub ssr_chunking_context: Option<ResolvedVc<Box<dyn ChunkingContext>>>,
pub rsc_chunking_context: Option<ResolvedVc<Box<dyn ChunkingContext>>>,
pub async_module_info: ResolvedVc<AsyncModulesInfo>,
pub next_config: ResolvedVc<NextConfig>,
pub runtime: NextRuntime,
......@@ -174,7 +173,6 @@ async fn build_manifest(
client_references_chunks,
client_chunking_context,
ssr_chunking_context,
rsc_chunking_context,
async_module_info,
next_config,
runtime,
......@@ -343,12 +341,15 @@ async fn build_manifest(
(Vec::new(), false)
};
let mut ssr_is_async = false;
if let Some(ssr_chunking_context) = *ssr_chunking_context {
let ssr_module = client_reference_module_ref.ssr_module;
let ssr_chunk_item_id = ssr_module.chunk_item_id(*ssr_chunking_context).await?;
let (ssr_chunks_paths, ssr_module_is_async) = if *runtime == NextRuntime::Edge {
let rsc_chunk_item_id = client_reference_module
.chunk_item_id(*ssr_chunking_context)
.await?;
let (ssr_chunks_paths, ssr_is_async) = if *runtime == NextRuntime::Edge {
// the chunks get added to the middleware-manifest.json instead
// of this file because the
// edge runtime doesn't support dynamically
......@@ -380,7 +381,26 @@ async fn build_manifest(
} else {
(Vec::new(), false)
};
ssr_is_async = ssr_module_is_async;
let rsc_is_async = if *runtime == NextRuntime::Edge {
false
} else {
async_modules.contains(&ResolvedVc::upcast(client_reference_module))
};
entry_manifest.client_modules.module_exports.insert(
get_client_reference_module_key(&server_path, "*"),
ManifestNodeEntry {
name: rcstr!("*"),
id: (&client_chunk_item_id).into(),
chunks: client_chunks_paths,
// This should of course be client_is_async, but SSR can become
// async due to ESM externals, and
// the ssr_manifest_node is currently ignored
// by React.
r#async: client_is_async || ssr_is_async,
},
);
let mut ssr_manifest_node = ManifestNode::default();
ssr_manifest_node.module_exports.insert(
......@@ -392,36 +412,11 @@ async fn build_manifest(
.into_iter()
.map(ClientChunk::Path)
.collect(),
// See below
// See above
r#async: client_is_async || ssr_is_async,
},
);
match runtime {
NextRuntime::NodeJs => {
entry_manifest
.ssr_module_mapping
.insert((&client_chunk_item_id).into(), ssr_manifest_node);
}
NextRuntime::Edge => {
entry_manifest
.edge_ssr_module_mapping
.insert((&client_chunk_item_id).into(), ssr_manifest_node);
}
}
}
if let Some(rsc_chunking_context) = *rsc_chunking_context {
let rsc_chunk_item_id = client_reference_module
.chunk_item_id(*rsc_chunking_context)
.await?;
let rsc_is_async = if *runtime == NextRuntime::Edge {
false
} else {
async_modules.contains(&ResolvedVc::upcast(client_reference_module))
};
let mut rsc_manifest_node = ManifestNode::default();
rsc_manifest_node.module_exports.insert(
rcstr!("*"),
......@@ -435,33 +430,23 @@ async fn build_manifest(
match runtime {
NextRuntime::NodeJs => {
entry_manifest
.ssr_module_mapping
.insert((&client_chunk_item_id).into(), ssr_manifest_node);
entry_manifest
.rsc_module_mapping
.insert((&client_chunk_item_id).into(), rsc_manifest_node);
}
NextRuntime::Edge => {
entry_manifest
.edge_ssr_module_mapping
.insert((&client_chunk_item_id).into(), ssr_manifest_node);
entry_manifest
.edge_rsc_module_mapping
.insert((&client_chunk_item_id).into(), rsc_manifest_node);
}
}
}
if ssr_chunking_context.is_some() || rsc_chunking_context.is_some() {
entry_manifest.client_modules.module_exports.insert(
get_client_reference_module_key(&server_path, "*"),
ManifestNodeEntry {
name: rcstr!("*"),
id: (&client_chunk_item_id).into(),
chunks: client_chunks_paths,
// This should of course be client_is_async, but SSR can become
// async due to ESM externals, and
// the ssr_manifest_node is currently ignored
// by React.
r#async: client_is_async || ssr_is_async,
},
);
}
}
// per layout segment chunks need to be emitted into the manifest too
......
......@@ -6,7 +6,6 @@ use napi::{JsFunction, bindgen_prelude::External};
use napi_derive::napi;
use next_api::{
operation::OptionEndpoint,
output_mode::mark_as_ssr,
paths::AssetPath,
route::{
Endpoint, EndpointOutputPaths, endpoint_client_changed_operation,
......@@ -150,8 +149,6 @@ async fn get_written_endpoint_with_issues_operation(
#[napi]
pub async fn endpoint_write_to_disk(
#[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: External<ExternalEndpoint>,
// Only passed for app page HTML endpoints
rsc_only: Option<bool>,
) -> napi::Result<TurbopackResult<NapiWrittenEndpoint>> {
let ctx = endpoint.turbopack_ctx();
let endpoint_op = ***endpoint;
......@@ -159,9 +156,6 @@ pub async fn endpoint_write_to_disk(
.turbopack_ctx()
.turbo_tasks()
.run(async move {
if rsc_only == Some(false) {
mark_as_ssr(endpoint_op).await?;
}
let written_entrypoint_with_issues_op =
get_written_endpoint_with_issues_operation(endpoint_op);
let read = read_strongly_consistent_and_apply_effects(
......
......@@ -168,10 +168,9 @@ export interface NapiWrittenEndpoint {
serverPaths: Array<NapiAssetPath>
config: NapiEndpointConfig
}
export declare function endpointWriteToDisk(
endpoint: { __napiType: 'Endpoint' },
rscOnly?: boolean | undefined | null
): Promise<TurbopackResult>
export declare function endpointWriteToDisk(endpoint: {
__napiType: 'Endpoint'
}): Promise<TurbopackResult>
export declare function endpointServerChangedSubscribe(
endpoint: { __napiType: 'Endpoint' },
issues: boolean,
......
......@@ -864,12 +864,9 @@ function bindingToApi(
this._nativeEndpoint = nativeEndpoint
}
async writeToDisk(
rscOnly?: boolean
): Promise<TurbopackResult<WrittenEndpoint>> {
async writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> {
return (await binding.endpointWriteToDisk(
this._nativeEndpoint,
rscOnly
this._nativeEndpoint
)) as TurbopackResult<WrittenEndpoint>
}
......
......@@ -387,14 +387,8 @@ export type Route =
}
export interface Endpoint {
/**
* Write files for the endpoint to disk.
*
* `rscOnly` must only be passed for app page HTML endpoints. When true,
* the page is compiled without its Client Component SSR chunks unless it
* has previously been written for a document render.
*/
writeToDisk(rscOnly?: boolean): Promise<TurbopackResult<WrittenEndpoint>>
/** Write files for the endpoint to disk. */
writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>>
/**
* Listen to client-side changes to the endpoint.
......
......@@ -134,10 +134,7 @@ import {
isAppRouteRouteModule,
} from './route-modules/checks'
import { NextDataPathnameNormalizer } from './normalizers/request/next-data'
import {
getIsPossibleServerAction,
getServerActionRequestMetadata,
} from './lib/server-action-request-meta'
import { getIsPossibleServerAction } from './lib/server-action-request-meta'
import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'
import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
......@@ -2665,22 +2662,6 @@ export default abstract class Server<
): Promise<LoadComponentsReturnType<ErrorModule> | null>
protected abstract getRoutesManifest(): NormalizedRouteManifest | undefined
protected matchOptions(req: ServerRequest, pathname: string): MatchOptions {
return {
i18n: this.i18nProvider?.fromRequest(req, pathname),
// Only actual navigations and fetch actions compile the SSR-free output
// — never prefetches. With cache components, a prefetch triggers a dev
// validation render that consumes the Flight payload through
// `ssrModuleMapping`, which the SSR-free output doesn't emit. Fetch
// actions always respond with a Flight payload, unlike no-JS form
// actions, which respond with an HTML document.
rscOnly:
(!!getRequestMeta(req, 'isRSCRequest') &&
!getRequestMeta(req, 'isPrefetchRSCRequest')) ||
getServerActionRequestMetadata(req).isFetchAction,
}
}
private async renderToResponseImpl(
ctx: RequestContext<ServerRequest, ServerResponse>
): Promise<ResponsePayload | null> {
......@@ -2701,7 +2682,9 @@ export default abstract class Server<
}
delete query[NEXT_RSC_UNION_QUERY]
const options = this.matchOptions(req, pathname)
const options: MatchOptions = {
i18n: this.i18nProvider?.fromRequest(req, pathname),
}
const existingMatch = getRequestMeta(ctx.req, 'match')
......
......@@ -1656,7 +1656,6 @@ export async function createHotReloaderTurbopack(
definition,
isApp,
url: requestUrl,
rscOnly,
subscribeToChanges = true,
}) {
// When there is no route definition this is an internal file not a route the user added.
......@@ -1803,7 +1802,6 @@ export async function createHotReloaderTurbopack(
entrypoints: currentEntrypoints,
manifestLoader,
readyIds,
rscOnly,
devRewrites: opts.fsChecker.rewrites,
productionRewrites: undefined,
logErrors: true,
......
......@@ -287,7 +287,6 @@ export interface NextJsHotReloaderInterface {
isApp?: boolean
definition?: RouteDefinition
url?: string
rscOnly?: boolean
/**
* Whether to wire HMR change subscriptions for the compiled entry.
* Defaults to true (the dev server uses these to push updates to
......
......@@ -235,13 +235,12 @@ export default class DevServer extends Server {
const { pagesDir, appDir } = findPagesDir(this.dir)
const ensurer: RouteEnsurer = {
ensure: async (match, pathname, options) => {
ensure: async (match, pathname) => {
await this.ensurePage({
definition: match.definition,
page: match.definition.page,
clientOnly: false,
url: pathname,
rscOnly: options?.rscOnly,
})
},
}
......@@ -983,7 +982,6 @@ export default class DevServer extends Server {
appPaths?: ReadonlyArray<string> | null
definition: RouteDefinition | undefined
url?: string
rscOnly?: boolean
}): Promise<void> {
await this.bundlerService.ensurePage(opts)
}
......
......@@ -152,7 +152,6 @@ export async function handleRouteType({
entrypoints,
manifestLoader,
readyIds,
rscOnly,
devRewrites,
productionRewrites,
hooks,
......@@ -172,8 +171,6 @@ export async function handleRouteType({
readyIds?: ReadyIds // dev
rscOnly?: boolean
// hooks.subscribeToChanges may be omitted to skip HMR subscriptions for
// one-shot compilations (e.g. the compile_route MCP tool).
hooks?: HandleRouteTypeHooks // dev
......@@ -349,9 +346,7 @@ export async function handleRouteType({
case 'app-page': {
const key = getEntryKey('app', 'server', page)
const writtenEndpoint = await route.htmlEndpoint.writeToDisk(
rscOnly ?? false
)
const writtenEndpoint = await route.htmlEndpoint.writeToDisk()
hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)
if (dev) {
......
......@@ -95,6 +95,7 @@ import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
import { isPagesAPIRouteMatch } from './route-matches/pages-api-route-match'
import type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'
import type { MatchOptions } from './route-matcher-managers/route-matcher-manager'
import { BubbledError, getTracer } from './lib/trace/tracer'
import { NextNodeServerSpan } from './lib/trace/constants'
import { nodeFs } from './lib/node-fs-methods'
......@@ -1113,7 +1114,9 @@ export default class NextNodeServer extends BaseServer<
// next.js core assumes page path without trailing slash
pathname = removeTrailingSlash(pathname)
const options = super.matchOptions(req, pathname)
const options: MatchOptions = {
i18n: this.i18nProvider?.fromRequest(req, pathname),
}
const match = await this.matchers.match(pathname, options)
// If we don't have a match, try to render it anyways.
......
......@@ -9,11 +9,7 @@ import { cyan } from '../../lib/picocolors'
import type { RouteMatcher } from '../route-matchers/route-matcher'
export interface RouteEnsurer {
ensure(
match: RouteMatch,
pathname: string,
options?: MatchOptions
): Promise<void>
ensure(match: RouteMatch, pathname: string): Promise<void>
}
export class DevRouteMatcherManager extends DefaultRouteMatcherManager {
......@@ -74,7 +70,7 @@ export class DevRouteMatcherManager extends DefaultRouteMatcherManager {
for await (const developmentMatch of super.matchAll(pathname, options)) {
// We're here, which means that we haven't seen this match yet, so we
// should try to ensure it and recompile the production matcher.
await this.ensurer.ensure(developmentMatch, pathname, options)
await this.ensurer.ensure(developmentMatch, pathname)
await this.production.reload()
// Iterate over the production matches again, this time we should be able
......
......@@ -11,8 +11,6 @@ export type MatchOptions = {
* application was not configured for additional locales.
*/
i18n?: LocaleAnalysisResult | undefined
rscOnly?: boolean
}
export interface RouteMatcherManager {
......
'use client'
import { useState } from 'react'
export function Counter({ label }: { label: string }) {
const [count, setCount] = useState(0)
return (
<button id={`${label}-button`} onClick={() => setCount((c) => c + 1)}>
{label} count: {count}
</button>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
import { Counter } from '../counter'
export default function Other() {
return (
<main>
<h1 id="other-heading">Other page</h1>
<p id="other-text">server rendered text on other</p>
<Counter label="other" />
<Link href="/" id="to-home">
Back home
</Link>
</main>
)
}
import Link from 'next/link'
import { Counter } from './counter'
export default function Page() {
return (
<main>
<h1 id="home-heading">Home page</h1>
<Counter label="home" />
<Link href="/other" id="to-other">
Go to other
</Link>
</main>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { copyFileSync, unlinkSync } from 'fs'
import { tmpdir } from 'os'
import { randomUUID } from 'crypto'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// In dev, Turbopack compiles an SSR-free variant on soft navigations; navigation
// and rendering must stay correct. Webpack always renders SSR, so it must behave
// identically.
describe('app dir - dev skip ssr on navigation', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
// Loads the client-reference manifest that the most recent compile of
// `/other` wrote to disk. Requires a unique copy of the file: Jest caches
// both the module registry and file contents for the duration of a test
// file, so requiring the manifest path directly would return a stale
// manifest after a recompile changed it on disk.
function loadOtherPageClientReferenceManifest() {
const manifestPath = path.join(
next.testDir,
'.next/dev/server/app/other/page_client-reference-manifest.js'
)
const tempPath = path.join(
tmpdir(),
`client-reference-manifest-${randomUUID()}.js`
)
copyFileSync(manifestPath, tempPath)
delete (globalThis as any).__RSC_MANIFEST
try {
// Sets globalThis.__RSC_MANIFEST
require(tempPath)
return (globalThis as any).__RSC_MANIFEST['/other/page']
} finally {
delete (globalThis as any).__RSC_MANIFEST
unlinkSync(tempPath)
}
}
it('server-renders the initial page as full HTML', async () => {
const $ = await next.render$('/')
expect($('#home-heading').text()).toBe('Home page')
expect($('#home-button').text()).toContain('home count: 0')
expect($('html').length).toBe(1)
})
it('hydrates and keeps Client Components interactive', async () => {
const browser = await next.browser('/')
await browser.elementById('home-button').click()
await retry(async () => {
expect(await browser.elementById('home-button').text()).toContain(
'home count: 1'
)
})
})
it('soft-navigates to another route and renders it correctly', async () => {
const browser = await next.browser('/')
await browser.elementById('to-other').click()
await retry(async () => {
expect(await browser.elementById('other-heading').text()).toBe(
'Other page'
)
})
expect(await browser.elementById('other-text').text()).toBe(
'server rendered text on other'
)
await browser.elementById('other-button').click()
await retry(async () => {
expect(await browser.elementById('other-button').text()).toContain(
'other count: 1'
)
})
if (isTurbopack) {
// The route was only ever soft-navigated to, so it must have been
// compiled without SSR: client and RSC module mappings are emitted,
// but no Client Component SSR chunks were built.
const manifest = loadOtherPageClientReferenceManifest()
expect(Object.keys(manifest.clientModules).length).toBeGreaterThan(0)
expect(Object.keys(manifest.rscModuleMapping).length).toBeGreaterThan(0)
expect(manifest.ssrModuleMapping).toEqual({})
}
})
it('hard-loads a route that was previously only soft-navigated with full SSR HTML', async () => {
// Soft-navigate first so the route is compiled via the SSR-free variant.
const browser = await next.browser('/')
await browser.elementById('to-other').click()
await retry(async () => {
expect(await browser.elementById('other-heading').text()).toBe(
'Other page'
)
})
// The hard load must still return full SSR HTML (compiles the full endpoint).
const $ = await next.render$('/other')
expect($('#other-heading').text()).toBe('Other page')
expect($('#other-text').text()).toBe('server rendered text on other')
expect($('#other-button').text()).toContain('other count: 0')
expect($('html').length).toBe(1)
if (isTurbopack) {
// The hard load recompiled the route with SSR, which emits the SSR
// module mapping again.
const manifest = loadOtherPageClientReferenceManifest()
expect(Object.keys(manifest.ssrModuleMapping).length).toBeGreaterThan(0)
}
})
})
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