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

Add buildId into RSC payload #50974

Merged
merged 21 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,11 @@ async function runOperation(renderData: RenderData) {
const renderOpt: Omit<
RenderOpts,
'App' | 'Document' | 'Component' | 'pathname'
> & { params: ParsedUrlQuery } = {
> & {
params: ParsedUrlQuery
} = {
// TODO: give an actual buildId when next build is supported
buildId: 'development',
params: renderData.params,
supportsDynamicHTML: true,
dev: true,
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/client/app-index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ export function hydrate() {
reactRoot.render(
<GlobalLayoutRouterContext.Provider
value={{
buildId: 'development',
tree: rootLayoutMissingTagsError.tree,
changeByServerResponse: () => {},
focusAndScrollRef: {
Expand Down
19 changes: 18 additions & 1 deletion packages/next/src/client/components/app-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ export function getServerActionDispatcher() {
export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin)
urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)
if (process.env.NODE_ENV === 'production') {
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
if (urlWithoutFlightParameters.pathname.endsWith('/index.txt')) {
// Slice off `/index.txt` from the end of the pathname
urlWithoutFlightParameters.pathname =
urlWithoutFlightParameters.pathname.slice(0, -`/index.txt`.length)
} else {
// Slice off `.txt` from the end of the pathname
urlWithoutFlightParameters.pathname =
urlWithoutFlightParameters.pathname.slice(0, -`.txt`.length)
}
}
}
return urlWithoutFlightParameters
}

Expand All @@ -82,6 +95,7 @@ type AppRouterProps = Omit<
Omit<InitialRouterStateParameters, 'isServer' | 'location'>,
'initialParallelRoutes'
> & {
buildId: string
initialHead: ReactNode
assetPrefix: string
// Top level boundaries props
Expand Down Expand Up @@ -123,6 +137,7 @@ function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) {
* The global router that wraps the application components.
*/
function Router({
buildId,
initialHead,
initialTree,
initialCanonicalUrl,
Expand All @@ -135,6 +150,7 @@ function Router({
const initialState = useMemo(
() =>
createInitialRouterState({
buildId,
children,
initialCanonicalUrl,
initialTree,
Expand All @@ -143,7 +159,7 @@ function Router({
location: !isServer ? window.location : null,
initialHead,
}),
[children, initialCanonicalUrl, initialTree, initialHead]
[buildId, children, initialCanonicalUrl, initialTree, initialHead]
)
const [
{
Expand Down Expand Up @@ -444,6 +460,7 @@ function Router({
<SearchParamsContext.Provider value={searchParams}>
<GlobalLayoutRouterContext.Provider
value={{
buildId,
changeByServerResponse,
tree,
focusAndScrollRef,
Expand Down
5 changes: 3 additions & 2 deletions packages/next/src/client/components/layout-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ function InnerLayoutRouter({
throw new Error('invariant global layout router not mounted')
}

const { changeByServerResponse, tree: fullTree } = context
const { buildId, changeByServerResponse, tree: fullTree } = context

// Read segment path from the parallel router cache node.
let childNode = childNodes.get(cacheKey)
Expand Down Expand Up @@ -368,7 +368,8 @@ function InnerLayoutRouter({
data: fetchServerResponse(
new URL(url, location.origin),
refetchTree,
context.nextUrl
context.nextUrl,
buildId
),
subTreeData: null,
head:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type { FlightRouterState } from '../../../server/app-render/types'
import { CacheNode, CacheStates } from '../../../shared/lib/app-router-context'
import { createInitialRouterState } from './create-initial-router-state'

const buildId = 'development'

const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
Expand Down Expand Up @@ -31,6 +33,7 @@ describe('createInitialRouterState', () => {
const initialParallelRoutes: CacheNode['parallelRoutes'] = new Map()

const state = createInitialRouterState({
buildId,
initialTree,
initialCanonicalUrl,
children,
Expand All @@ -41,6 +44,7 @@ describe('createInitialRouterState', () => {
})

const state2 = createInitialRouterState({
buildId,
initialTree,
initialCanonicalUrl,
children,
Expand Down Expand Up @@ -89,6 +93,7 @@ describe('createInitialRouterState', () => {
}

const expected: ReturnType<typeof createInitialRouterState> = {
buildId,
tree: initialTree,
canonicalUrl: initialCanonicalUrl,
prefetchCache: new Map(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-
import { extractPathFromFlightRouterState } from './compute-changed-path'

export interface InitialRouterStateParameters {
buildId: string
initialTree: FlightRouterState
initialCanonicalUrl: string
children: ReactNode
Expand All @@ -18,6 +19,7 @@ export interface InitialRouterStateParameters {
}

export function createInitialRouterState({
buildId,
initialTree,
children,
initialCanonicalUrl,
Expand All @@ -40,6 +42,7 @@ export function createInitialRouterState({
}

return {
buildId,
tree: initialTree,
cache,
prefetchCache: new Map(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createFromFetch } from 'react-server-dom-webpack/client'
import type {
FlightRouterState,
FlightData,
NextFlightResponse,
} from '../../../server/app-render/types'
import {
NEXT_ROUTER_PREFETCH,
Expand All @@ -20,16 +21,25 @@ import { callServer } from '../../app-call-server'
import { PrefetchKind } from './router-reducer-types'
import { hexHash } from '../../../shared/lib/hash'

type FetchServerResponseResult = [
flightData: FlightData,
canonicalUrlOverride: URL | undefined
]

function doMpaNavigation(url: string): FetchServerResponseResult {
return [urlToUrlWithoutFlightMarker(url).toString(), undefined]
}

/**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
*/

export async function fetchServerResponse(
url: URL,
flightRouterState: FlightRouterState,
nextUrl: string | null,
currentBuildId: string,
prefetchKind?: PrefetchKind
): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> {
): Promise<FetchServerResponseResult> {
const headers: {
[RSC]: '1'
[NEXT_ROUTER_STATE_TREE]: string
Expand Down Expand Up @@ -103,13 +113,21 @@ export async function fetchServerResponse(
// If fetch returns something different than flight response handle it like a mpa navigation
// If the fetch was not 200, we also handle it like a mpa navigation
if (!isFlightResponse || !res.ok) {
return [responseUrl.toString(), undefined]
return doMpaNavigation(responseUrl.toString())
}

// Handle the `fetch` readable stream that can be unwrapped by `React.use`.
const flightData: FlightData = await createFromFetch(Promise.resolve(res), {
callServer,
})
const [buildId, flightData]: NextFlightResponse = await createFromFetch(
Promise.resolve(res),
{
callServer,
}
)

if (currentBuildId !== buildId) {
return doMpaNavigation(res.url)
}

return [flightData, canonicalUrl]
} catch (err) {
console.error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function handleMutable(
mutable: Mutable
): ReducerState {
return {
buildId: state.buildId,
// Set href.
canonicalUrl:
typeof mutable.canonicalUrl !== 'undefined'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ function fastRefreshReducerImpl(
fetchServerResponse(
new URL(href, origin),
[state.tree[0], state.tree[1], state.tree[2], 'refetch'],
state.nextUrl
state.nextUrl,
state.buildId
)
)
}
Expand Down
Loading