Unverified Commit 2dc0ba4b authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

app router: support side effects on server requests (#48939)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

link NEXT-920

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 248f2def
......@@ -88,8 +88,8 @@ const babelIncludeRegexes: RegExp[] = [
const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/
const staticGenerationAsyncStorageRegex =
/next[\\/]dist[\\/]client[\\/]components[\\/]static-generation-async-storage/
const asyncStoragesRegex =
/next[\\/]dist[\\/]client[\\/]components[\\/](static-generation-async-storage|action-async-storage)/
const mainFieldsPerCompiler: Record<CompilerNameValues, string[]> = {
[COMPILER_NAMES.server]: ['main', 'module'],
......@@ -1841,10 +1841,7 @@ export default async function getBaseWebpackConfig(
and: [
codeCondition.test,
{
not: [
optOutBundlingPackageRegex,
staticGenerationAsyncStorageRegex,
],
not: [optOutBundlingPackageRegex, asyncStoragesRegex],
},
],
},
......@@ -1866,7 +1863,7 @@ export default async function getBaseWebpackConfig(
// Make sure that AsyncLocalStorage module instance is shared between server and client
// layers.
layer: WEBPACK_LAYERS.shared,
test: staticGenerationAsyncStorageRegex,
test: asyncStoragesRegex,
},
]
: []),
......@@ -1900,7 +1897,7 @@ export default async function getBaseWebpackConfig(
// Alias react for switching between default set and share subset.
oneOf: [
{
exclude: [staticGenerationAsyncStorageRegex],
exclude: [asyncStoragesRegex],
issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
},
......@@ -1974,7 +1971,7 @@ export default async function getBaseWebpackConfig(
issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
},
exclude: [staticGenerationAsyncStorageRegex],
exclude: [asyncStoragesRegex],
use: swcLoaderForServerLayer,
},
{
......@@ -1987,10 +1984,7 @@ export default async function getBaseWebpackConfig(
issuerLayer: {
or: [WEBPACK_LAYERS.client, WEBPACK_LAYERS.appClient],
},
exclude: [
staticGenerationAsyncStorageRegex,
codeCondition.exclude,
],
exclude: [asyncStoragesRegex, codeCondition.exclude],
use: [
...(dev && isClient
? [
......
// @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies
import { encodeReply } from 'react-server-dom-webpack/client'
import { getServerActionDispatcher } from './components/app-router'
export async function callServer(id: string, args: any[]) {
const actionId = id
export async function callServer(actionId: string, actionArgs: any[]) {
const actionDispatcher = getServerActionDispatcher()
// Fetching the current url with the action header.
// TODO: Refactor this to look up from a manifest.
const res = await fetch('', {
method: 'POST',
headers: { Accept: 'text/x-component', 'Next-Action': actionId },
body: await encodeReply(args),
})
if (!res.ok) {
throw new Error(await res.text())
if (!actionDispatcher) {
throw new Error('Invariant: missing action dispatcher.')
}
return (await res.json())[0]
return new Promise((resolve, reject) => {
actionDispatcher({
actionId,
actionArgs,
resolve,
reject,
})
})
}
......@@ -24,8 +24,12 @@ import {
ACTION_PREFETCH,
ACTION_REFRESH,
ACTION_RESTORE,
ACTION_SERVER_ACTION,
ACTION_SERVER_PATCH,
PrefetchKind,
RouterChangeByServerResponse,
RouterNavigate,
ServerActionDispatcher,
} from './router-reducer/router-reducer-types'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import {
......@@ -53,6 +57,12 @@ let initialParallelRoutes: CacheNode['parallelRoutes'] = isServer
? null!
: new Map()
let globalServerActionDispatcher = null as ServerActionDispatcher | null
export function getServerActionDispatcher() {
return globalServerActionDispatcher
}
export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin)
// TODO-APP: handle .rsc for static export case
......@@ -170,7 +180,7 @@ function Router({
/**
* Server response that only patches the cache and tree.
*/
const changeByServerResponse = useCallback(
const changeByServerResponse: RouterChangeByServerResponse = useCallback(
(
previousTree: FlightRouterState,
flightData: FlightData,
......@@ -193,11 +203,8 @@ function Router({
[dispatch]
)
/**
* The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state.
*/
const appRouter = useMemo<AppRouterInstance>(() => {
const navigate = (
const navigate: RouterNavigate = useCallback(
(
href: string,
navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean
......@@ -219,8 +226,31 @@ function Router({
},
mutable: {},
})
}
},
[dispatch]
)
const serverActionDispatcher: ServerActionDispatcher = useCallback(
(actionPayload) => {
React.startTransition(() => {
dispatch({
...actionPayload,
type: ACTION_SERVER_ACTION,
mutable: {},
navigate,
changeByServerResponse,
})
})
},
[changeByServerResponse, dispatch, navigate]
)
globalServerActionDispatcher = serverActionDispatcher
/**
* The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state.
*/
const appRouter = useMemo<AppRouterInstance>(() => {
const routerInstance: AppRouterInstance = {
back: () => window.history.back(),
forward: () => window.history.forward(),
......@@ -297,13 +327,18 @@ function Router({
}
return routerInstance
}, [dispatch])
}, [dispatch, navigate])
// Add `window.nd` for debugging purposes.
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
if (typeof window !== 'undefined') {
// @ts-ignore this is for debugging
window.nd = { router: appRouter, cache, prefetchCache, tree }
window.nd = {
router: appRouter,
cache,
prefetchCache,
tree,
}
}
// When mpaNavigation flag is set do a hard navigation to the new url.
......
......@@ -2,7 +2,12 @@
import React, { useEffect } from 'react'
import { AppRouterInstance } from '../../shared/lib/app-router-context'
import { useRouter } from './navigation'
import { getURLFromRedirectError, isRedirectError } from './redirect'
import {
RedirectType,
getRedirectTypeFromError,
getURLFromRedirectError,
isRedirectError,
} from './redirect'
interface RedirectBoundaryProps {
router: AppRouterInstance
......@@ -12,8 +17,10 @@ interface RedirectBoundaryProps {
function HandleRedirect({
redirect,
reset,
redirectType,
}: {
redirect: string
redirectType: RedirectType
reset: () => void
}) {
const router = useRouter()
......@@ -21,38 +28,44 @@ function HandleRedirect({
useEffect(() => {
// @ts-ignore startTransition exists
React.startTransition(() => {
router.replace(redirect, {})
if (redirectType === RedirectType.push) {
router.push(redirect, {})
} else {
router.replace(redirect, {})
}
reset()
})
}, [redirect, reset, router])
}, [redirect, redirectType, reset, router])
return null
}
export class RedirectErrorBoundary extends React.Component<
RedirectBoundaryProps,
{ redirect: string | null }
{ redirect: string | null; redirectType: RedirectType | null }
> {
constructor(props: RedirectBoundaryProps) {
super(props)
this.state = { redirect: null }
this.state = { redirect: null, redirectType: null }
}
static getDerivedStateFromError(error: any) {
if (isRedirectError(error)) {
const url = getURLFromRedirectError(error)
return { redirect: url }
const redirectType = getRedirectTypeFromError(error)
return { redirect: url, redirectType }
}
// Re-throw if error is not for redirect
throw error
}
render() {
const redirect = this.state.redirect
if (redirect !== null) {
const { redirect, redirectType } = this.state
if (redirect !== null && redirectType !== null) {
return (
<HandleRedirect
redirect={redirect}
redirectType={redirectType}
reset={() => this.setState({ redirect: null })}
/>
)
......
const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'
export enum RedirectType {
push = 'push',
replace = 'replace',
}
type RedirectError<U extends string> = Error & {
digest: `${typeof REDIRECT_ERROR_CODE};${U}`
digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${U}`
}
export function getRedirectError(
url: string,
type: RedirectType
): RedirectError<typeof url> {
// eslint-disable-next-line no-throw-literal
const error = new Error(REDIRECT_ERROR_CODE)
;(
error as RedirectError<typeof url>
).digest = `${REDIRECT_ERROR_CODE};${type};${url}`
return error as RedirectError<typeof url>
}
/**
......@@ -11,11 +28,11 @@ type RedirectError<U extends string> = Error & {
*
* @param url the url to redirect to
*/
export function redirect(url: string): never {
// eslint-disable-next-line no-throw-literal
const error = new Error(REDIRECT_ERROR_CODE)
;(error as RedirectError<typeof url>).digest = `${REDIRECT_ERROR_CODE};${url}`
throw error
export function redirect(
url: string,
type: RedirectType = RedirectType.replace
): never {
throw getRedirectError(url, type)
}
/**
......@@ -28,10 +45,14 @@ export function redirect(url: string): never {
export function isRedirectError<U extends string>(
error: any
): error is RedirectError<U> {
if (typeof error?.digest !== 'string') return false
const [errorCode, type, destination] = (error.digest as string).split(';', 3)
return (
typeof error?.digest === 'string' &&
error.digest.startsWith(REDIRECT_ERROR_CODE + ';') &&
error.digest.length > REDIRECT_ERROR_CODE.length + 1
errorCode === REDIRECT_ERROR_CODE &&
(type === 'replace' || type === 'push') &&
typeof destination === 'string'
)
}
......@@ -45,11 +66,20 @@ export function isRedirectError<U extends string>(
export function getURLFromRedirectError<U extends string>(
error: RedirectError<U>
): U
export function getURLFromRedirectError(error: any): string | null
export function getURLFromRedirectError(error: any): string | null {
if (!isRedirectError(error)) return null
// Slices off the beginning of the digest that contains the code and the
// separating ';'.
return error.digest.slice(REDIRECT_ERROR_CODE.length + 1)
return error.digest.split(';', 3)[2]
}
export function getRedirectTypeFromError<U extends string>(
error: RedirectError<U>
): RedirectType {
if (!isRedirectError(error)) {
throw new Error('Not a redirect error')
}
return error.digest.split(';', 3)[1] as RedirectType
}
......@@ -140,7 +140,7 @@ export function navigateReducer(
) {
const segments = pathname.split('/')
// TODO-APP: figure out something better for index pages
segments.push('')
segments.push('__PAGE__')
// Optimistic tree case.
// If the optimistic tree is deeper than the current state leave that deeper part out of the fetch
......@@ -165,7 +165,7 @@ export function navigateReducer(
// TODO-APP: re-evaluate if we need to strip the last segment
const optimisticFlightSegmentPath = segments
.slice(1)
.map((segment) => ['children', segment === '' ? '__PAGE__' : segment])
.map((segment) => ['children', segment])
.flat()
// Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch.
......
import {
ActionFlightData,
ActionResult,
FlightData,
} from '../../../../server/app-render/types'
import { callServer } from '../../../app-call-server'
import {
NEXT_ROUTER_STATE_TREE,
NEXT_URL,
RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
// eslint-disable-next-line import/no-extraneous-dependencies
import { createFromFetch } from 'react-server-dom-webpack/client'
// eslint-disable-next-line import/no-extraneous-dependencies
import { encodeReply } from 'react-server-dom-webpack/client'
import {
PrefetchKind,
ReadonlyReducerState,
ReducerState,
ServerActionAction,
} from '../router-reducer-types'
import { addBasePath } from '../../../add-base-path'
import { createHrefFromUrl } from '../create-href-from-url'
import { RedirectType, getRedirectError } from '../../redirect'
type FetchServerActionResult = {
redirectLocation: URL | undefined
actionResult?: ActionResult
actionFlightData?: FlightData | undefined | null
}
async function fetchServerAction(
state: ReadonlyReducerState,
{ actionId, actionArgs }: ServerActionAction
): Promise<FetchServerActionResult> {
const body = await encodeReply(actionArgs)
const res = await fetch('', {
method: 'POST',
headers: {
Accept: RSC_CONTENT_TYPE_HEADER,
'Next-Action': actionId,
[NEXT_ROUTER_STATE_TREE]: JSON.stringify(state.tree),
...(state.nextUrl
? {
[NEXT_URL]: state.nextUrl,
}
: {}),
},
body,
})
const location = res.headers.get('location')
const redirectLocation = location
? new URL(addBasePath(location), window.location.origin)
: undefined
let isFlightResponse =
res.headers.get('content-type') === RSC_CONTENT_TYPE_HEADER
if (isFlightResponse) {
const result = await createFromFetch(Promise.resolve(res), {
callServer,
})
// if it was a redirection, then result is just a regular RSC payload
if (location) {
return {
actionFlightData: result as FlightData,
redirectLocation,
}
// otherwise it's a tuple of [actionResult, actionFlightData]
} else {
const [actionResult, actionFlightData] =
(result as ActionFlightData | undefined) ?? []
return {
actionResult,
actionFlightData,
redirectLocation,
}
}
}
return {
redirectLocation,
}
}
/*
* This reducer is responsible for calling the server action and processing any side-effects from the server action.
* It does not mutate the state by itself but rather delegates to other reducers to do the actual mutation.
*/
export function serverActionReducer(
state: ReadonlyReducerState,
action: ServerActionAction
): ReducerState {
// the action could be called twice so we need to check if we already have applied it
if (action.mutable.serverActionApplied) {
return state
}
if (!action.mutable.inFlightServerAction) {
action.mutable.previousTree = state.tree
action.mutable.inFlightServerAction = createRecordFromThenable(
fetchServerAction(state, action)
)
}
// suspends until the server action is resolved.
const { actionResult, actionFlightData, redirectLocation } = readRecordValue(
action.mutable.inFlightServerAction!
) as Awaited<FetchServerActionResult>
if (redirectLocation) {
// the redirection might have a flight data associated with it, so we'll populate the cache with it
if (actionFlightData) {
const href = createHrefFromUrl(
redirectLocation,
// Ensures the hash is not part of the cache key as it does not affect fetching the server
false
)
state.prefetchCache.set(href, {
data: createRecordFromThenable(
Promise.resolve([
actionFlightData,
// TODO-APP: verify the logic around canonical URL overrides
undefined,
])
),
kind: PrefetchKind.TEMPORARY, //TODO-APP: maybe this could cached longer?
prefetchTime: Date.now(),
treeAtTimeOfPrefetch: action.mutable.previousTree!,
lastUsedTime: null,
})
}
// we throw the redirection in the action handler so that it is caught during render
action.reject(
getRedirectError(redirectLocation.toString(), RedirectType.push)
)
} else {
// TODO-APP: populate the prefetch cache with the new flight data
if (actionFlightData) {
// this is an intentional hack around React: we want to update the tree in a new render
setTimeout(() => {
action.changeByServerResponse(
action.mutable.previousTree!,
actionFlightData,
// TODO-APP: verify the logic around canonical URL overrides
undefined
)
})
}
action.resolve(actionResult)
}
action.mutable.serverActionApplied = true
return state
}
......@@ -12,6 +12,19 @@ export const ACTION_RESTORE = 'restore'
export const ACTION_SERVER_PATCH = 'server-patch'
export const ACTION_PREFETCH = 'prefetch'
export const ACTION_FAST_REFRESH = 'fast-refresh'
export const ACTION_SERVER_ACTION = 'server-action'
export type RouterChangeByServerResponse = (
previousTree: FlightRouterState,
flightData: FlightData,
overrideCanonicalUrl: URL | undefined
) => void
export type RouterNavigate = (
href: string,
navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean
) => void
export interface Mutable {
mpaNavigation?: boolean
......@@ -25,6 +38,12 @@ export interface Mutable {
hashFragment?: string
}
export interface ServerActionMutable {
inFlightServerAction?: Promise<any> | null
serverActionApplied?: boolean
previousTree?: FlightRouterState
}
/**
* Refresh triggers a refresh of the full page data.
* - fetches the Flight data and fills subTreeData at the root of the cache.
......@@ -44,6 +63,24 @@ export interface FastRefreshAction {
origin: Location['origin']
}
export type ServerActionDispatcher = (
args: Omit<
ServerActionAction,
'type' | 'mutable' | 'navigate' | 'changeByServerResponse'
>
) => void
export interface ServerActionAction {
type: typeof ACTION_SERVER_ACTION
actionId: string
actionArgs: any[]
resolve: (value: any) => void
reject: (reason?: any) => void
mutable: ServerActionMutable
navigate: RouterNavigate
changeByServerResponse: RouterChangeByServerResponse
}
/**
* Navigate triggers a navigation to the provided url. It supports two types: `push` and `replace`.
*
......@@ -224,4 +261,5 @@ export type ReducerActions = Readonly<
| ServerPatchAction
| PrefetchAction
| FastRefreshAction
| ServerActionAction
>
......@@ -8,6 +8,7 @@ import {
ReducerState,
ReadonlyReducerState,
ACTION_FAST_REFRESH,
ACTION_SERVER_ACTION,
} from './router-reducer-types'
import { navigateReducer } from './reducers/navigate-reducer'
import { serverPatchReducer } from './reducers/server-patch-reducer'
......@@ -15,6 +16,7 @@ import { restoreReducer } from './reducers/restore-reducer'
import { refreshReducer } from './reducers/refresh-reducer'
import { prefetchReducer } from './reducers/prefetch-reducer'
import { fastRefreshReducer } from './reducers/fast-refresh-reducer'
import { serverActionReducer } from './reducers/server-action-reducer'
/**
* Reducer that handles the app-router state updates.
......@@ -42,6 +44,9 @@ function clientReducer(
case ACTION_PREFETCH: {
return prefetchReducer(state, action)
}
case ACTION_SERVER_ACTION: {
return serverActionReducer(state, action)
}
// This case should never be hit as dispatch is strongly typed.
default:
throw new Error('Unknown action')
......
......@@ -7,9 +7,9 @@ export interface StaticGenerationStore {
readonly pathname: string
readonly originalPathname?: string
readonly incrementalCache?: IncrementalCache
readonly isRevalidate?: boolean
readonly isOnDemandRevalidate?: boolean
readonly isPrerendering?: boolean
readonly isRevalidate?: boolean
forceDynamic?: boolean
fetchCache?:
......@@ -28,6 +28,7 @@ export interface StaticGenerationStore {
dynamicUsageStack?: string
nextFetchId?: number
pathWasRevalidated?: boolean
tags?: string[]
}
......
import type { IncomingMessage, ServerResponse } from 'http'
import type {
IncomingHttpHeaders,
IncomingMessage,
OutgoingHttpHeaders,
ServerResponse,
} from 'http'
import { ACTION } from '../../client/components/app-router-headers'
import {
ACTION,
RSC,
RSC_CONTENT_TYPE_HEADER,
} from '../../client/components/app-router-headers'
import { isNotFoundError } from '../../client/components/not-found'
import {
getURLFromRedirectError,
isRedirectError,
} from '../../client/components/redirect'
import RenderResult from '../render-result'
import { ActionRenderResult } from './action-render-result'
import { StaticGenerationStore } from '../../client/components/static-generation-async-storage'
import { FlightRenderResult } from './flight-render-result'
import { ActionResult } from './types'
import { ActionAsyncStorage } from '../../client/components/action-async-storage'
function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query)
......@@ -18,18 +30,143 @@ function formDataFromSearchQueryString(query: string) {
return formData
}
function nodeHeadersToRecord(
headers: IncomingHttpHeaders | OutgoingHttpHeaders
) {
const record: Record<string, string> = {}
for (const [key, value] of Object.entries(headers)) {
if (value !== undefined) {
record[key] = Array.isArray(value) ? value.join(', ') : `${value}`
}
}
return record
}
function getForwardedHeaders(
req: IncomingMessage,
res: ServerResponse
): Headers {
// Get request headers and cookies
const requestHeaders = req.headers
const requestCookies = requestHeaders['cookie'] ?? ''
// Get response headers and Set-Cookie header
const responseHeaders = res.getHeaders()
const rawSetCookies = responseHeaders['set-cookie']
const setCookies = (
Array.isArray(rawSetCookies) ? rawSetCookies : [rawSetCookies]
).map((setCookie) => {
// remove the suffixes like 'HttpOnly' and 'SameSite'
const [cookie] = `${setCookie}`.split(';')
return cookie
})
// Merge request and response headers
const mergedHeaders = {
...nodeHeadersToRecord(requestHeaders),
...nodeHeadersToRecord(responseHeaders),
}
// Merge cookies
const mergedCookies = requestCookies.split('; ').concat(setCookies).join('; ')
// Update the 'cookie' header with the merged cookies
mergedHeaders['cookie'] = mergedCookies
// Remove headers that should not be forwarded
delete mergedHeaders['transfer-encoding']
return new Headers(mergedHeaders)
}
function fetchIPv4v6(
url: URL,
init: RequestInit,
v6 = false
): Promise<Response> {
const hostname = url.hostname
if (!v6 && hostname === 'localhost') {
url.hostname = '127.0.0.1'
}
return fetch(url, init).catch((err) => {
if (err.code === 'ECONNREFUSED' && !v6) {
return fetchIPv4v6(url, init, true)
}
throw err
})
}
async function createRedirectRenderResult(
req: IncomingMessage,
res: ServerResponse,
redirectUrl: string,
staticGenerationStore: StaticGenerationStore
) {
// if we're redirecting to a relative path, we'll try to stream the response
if (redirectUrl.startsWith('/')) {
const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC, '1')
const host = req.headers['host']
const proto =
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
const fetchUrl = new URL(`${proto}://${host}${redirectUrl}`)
try {
const headResponse = await fetchIPv4v6(fetchUrl, {
method: 'HEAD',
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1,
},
})
if (
headResponse.headers.get('content-type') === RSC_CONTENT_TYPE_HEADER
) {
const response = await fetchIPv4v6(fetchUrl, {
method: 'GET',
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1,
},
})
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers) {
res.setHeader(key, value)
}
return new FlightRenderResult(response.body!)
}
} catch (err) {
// we couldn't stream the redirect response, so we'll just do a normal redirect
}
}
return new RenderResult(JSON.stringify({}))
}
export async function handleAction({
req,
res,
ComponentMod,
pathname,
serverActionsManifest,
generateFlight,
staticGenerationStore,
}: {
req: IncomingMessage
res: ServerResponse
ComponentMod: any
pathname: string
serverActionsManifest: any
generateFlight: (options: {
actionResult: ActionResult
skipFlight: boolean
}) => Promise<RenderResult>
staticGenerationStore: StaticGenerationStore
}): Promise<undefined | RenderResult | 'not-found'> {
let actionId = req.headers[ACTION.toLowerCase()] as string
const contentType = req.headers['content-type']
......@@ -60,9 +197,11 @@ export async function handleAction({
}
)
const { actionAsyncStorage } = ComponentMod
const { actionAsyncStorage } = ComponentMod as {
actionAsyncStorage: ActionAsyncStorage
}
let actionResult: ActionRenderResult
let actionResult: RenderResult | undefined
try {
await actionAsyncStorage.run({ isAction: true }, async () => {
......@@ -145,38 +284,71 @@ export async function handleAction({
ComponentMod.__next_app_webpack_require__(actionModId)[actionId]
const returnVal = await actionHandler.apply(null, bound)
const result = new ActionRenderResult(JSON.stringify([returnVal]))
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
actionResult = result
await Promise.all(staticGenerationStore.pendingRevalidates || [])
actionResult = await generateFlight({
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
})
}
})
if (actionResult!) {
if (actionResult) {
return actionResult
}
} catch (err) {
if (isRedirectError(err)) {
if (isFetchAction || process.env.NEXT_RUNTIME === 'edge') {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new Error('Invariant: not implemented.')
}
const redirectUrl = getURLFromRedirectError(err)
res.statusCode = 303
// if it's a fetch action, we don't want to mess with the status code
// and we'll handle it on the client router
res.setHeader('Location', redirectUrl)
return new ActionRenderResult(JSON.stringify({}))
await Promise.all(staticGenerationStore.pendingRevalidates || [])
if (isFetchAction) {
return createRedirectRenderResult(
req,
res,
redirectUrl,
staticGenerationStore
)
}
res.statusCode = 303
return new RenderResult('')
} else if (isNotFoundError(err)) {
if (isFetchAction) {
throw new Error('Invariant: not implemented.')
}
await Promise.all(staticGenerationStore.pendingRevalidates || [])
res.statusCode = 404
return 'not-found'
}
if (isFetchAction) {
res.statusCode = 500
return new RenderResult(
(err as Error)?.message ?? 'Internal Server Error'
)
const rejectedPromise = Promise.reject(err)
try {
// we need to await the promise to trigger the rejection early
// so that it's already handled by the time we call
// the RSC runtime. Otherwise, it will throw an unhandled
// promise rejection error in the renderer.
await rejectedPromise
} catch (_) {
// swallow error, it's gonna be handled on the client
}
return generateFlight({
actionResult: rejectedPromise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
})
}
throw err
......
import RenderResult from '../render-result'
/**
* Action Response is set to application/json for now, but could be changed in the future.
*/
export class ActionRenderResult extends RenderResult {
constructor(response: string) {
super(response, { contentType: 'application/json' })
}
}
import type { IncomingMessage, ServerResponse } from 'http'
import type {
ActionResult,
ChildProp,
DynamicParamTypesShort,
FlightData,
......@@ -936,7 +937,10 @@ export async function renderToHTMLOrFlight(
}
// Handle Flight render request. This is only used when client-side navigating. E.g. when you `router.push('/dashboard')` or `router.reload()`.
const generateFlight = async (): Promise<RenderResult> => {
const generateFlight = async (options?: {
actionResult: ActionResult
skipFlight: boolean
}): Promise<RenderResult> => {
/**
* Use router state to decide at what common layout to render the page.
* This can either be the common layout between two pages or a specific place to start rendering from using the "refetch" marker in the tree.
......@@ -1146,39 +1150,41 @@ export async function renderToHTMLOrFlight(
// Flight data that is going to be passed to the browser.
// Currently a single item array but in the future multiple patches might be combined in a single request.
const flightData: FlightData = (
await walkTreeWithFlightRouterState({
createSegmentPath: (child) => child,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState: providedFlightRouterState,
isFirst: true,
// For flight, render metadata inside leaf page
rscPayloadHead: (
<>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */}
<MetadataTree
key={requestId}
tree={loaderTree}
pathname={pathname}
searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment}
/>
{appUsingSizeAdjust ? <meta name="next-size-adjust" /> : null}
</>
),
injectedCSS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
asNotFound: pathname === '/404',
})
).map((path) => path.slice(1)) // remove the '' (root) segment
const flightData: FlightData | null = options?.skipFlight
? null
: (
await walkTreeWithFlightRouterState({
createSegmentPath: (child) => child,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState: providedFlightRouterState,
isFirst: true,
// For flight, render metadata inside leaf page
rscPayloadHead: (
<>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */}
<MetadataTree
key={requestId}
tree={loaderTree}
pathname={pathname}
searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment}
/>
{appUsingSizeAdjust ? <meta name="next-size-adjust" /> : null}
</>
),
injectedCSS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
asNotFound: pathname === '/404',
})
).map((path) => path.slice(1)) // remove the '' (root) segment
// For app dir, use the bundled version of Fizz renderer (renderToReadableStream)
// which contains the subset React.
const readable = ComponentMod.renderToReadableStream(
flightData,
options ? [options.actionResult, flightData] : flightData,
clientReferenceManifest.clientModules,
{
context: serverContexts,
......@@ -1551,7 +1557,10 @@ export async function renderToHTMLOrFlight(
ComponentMod,
pathname: renderOpts.pathname,
serverActionsManifest,
generateFlight,
staticGenerationStore,
})
if (actionRequestResult === 'not-found') {
return new RenderResult(await bodyResult({ asNotFound: true }))
} else if (actionRequestResult) {
......
......@@ -100,6 +100,10 @@ export type FlightDataPath =
*/
export type FlightData = Array<FlightDataPath> | string
export type ActionResult = Promise<any>
export type ActionFlightData = [ActionResult, FlightData | null]
/**
* Property holding the current subTreeData.
*/
......
......@@ -65,7 +65,7 @@ export async function sendRenderResult({
const payload = result.isDynamic() ? null : await result.toUnchunkedString()
if (payload) {
if (payload !== null) {
const etag = generateEtags ? generateETag(payload) : undefined
if (sendEtagResponse(req, res, etag)) {
return
......@@ -97,7 +97,7 @@ export async function sendRenderResult({
if (req.method === 'HEAD') {
res.end(null)
} else if (payload) {
} else if (payload !== null) {
res.end(payload)
} else {
await result.pipe(res)
......
......@@ -25,4 +25,7 @@ export function revalidateTag(tag: string) {
console.error(`revalidateTag failed for ${tag}`, err)
})
)
// TODO: only revalidate if the path matches
store.pathWasRevalidated = true
}
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
import { Request } from 'playwright-chromium'
const GENERIC_RSC_ERROR =
'Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.'
createNextDescribe(
'app-dir action handling',
......@@ -119,9 +123,12 @@ createNextDescribe(
await browser.elementByCss('#authed').click()
await check(() => {
return browser.elementByCss('h1').text()
}, 'Error: Unauthorized request')
await check(
() => {
return browser.elementByCss('h1').text()
},
isNextDev ? 'Error: Unauthorized request' : GENERIC_RSC_ERROR
)
await await browser.eval(`document.cookie = 'auth=1'`)
......@@ -205,11 +212,120 @@ createNextDescribe(
await await browser.eval(`document.cookie = 'auth=0'`)
await browser.elementByCss('#authed').click()
await check(
async () => {
const text = await browser.elementByCss('h1').text()
console.log('text', text)
return text && text.length > 0 ? text : 'failed'
},
isNextDev ? /Multipart form data is not supported/ : GENERIC_RSC_ERROR
)
})
})
describe('fetch actions', () => {
it('should handle redirect to a relative URL in a single pass', async () => {
const browser = await next.browser('/client')
await new Promise((resolve) => {
setTimeout(resolve, 3000)
})
let requests = []
browser.on('request', (req: Request) => {
requests.push(new URL(req.url()).pathname)
})
await browser.elementByCss('#redirect').click()
// no other requests should be made
expect(requests).toEqual(['/client'])
})
it('should handle regular redirects', async () => {
const browser = await next.browser('/client')
await browser.elementByCss('#redirect-external').click()
await check(async () => {
return browser.eval('window.location.toString()')
}, 'https://example.com/')
})
it('should handle revalidatePath', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
const thankYouNext = await browser.elementByCss('#thankyounext').text()
await browser.elementByCss('#revalidate-path').click()
await check(async () => {
const newRandomNumber = await browser
.elementByCss('#random-number')
.text()
const newJustPutIt = await browser.elementByCss('#justputit').text()
const newThankYouNext = await browser
.elementByCss('#thankyounext')
.text()
return newRandomNumber !== randomNumber &&
justPutIt !== newJustPutIt &&
thankYouNext !== newThankYouNext
? 'success'
: 'failure'
}, 'success')
})
it('should handle revalidateTag', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
const thankYouNext = await browser.elementByCss('#thankyounext').text()
await browser.elementByCss('#revalidate-justputit').click()
await check(async () => {
const newRandomNumber = await browser
.elementByCss('#random-number')
.text()
const newJustPutIt = await browser.elementByCss('#justputit').text()
const newThankYouNext = await browser
.elementByCss('#thankyounext')
.text()
return newRandomNumber !== randomNumber &&
justPutIt !== newJustPutIt &&
thankYouNext === newThankYouNext
? 'success'
: 'failure'
}, 'success')
})
it('should handle revalidateTag + redirect', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
const thankYouNext = await browser.elementByCss('#thankyounext').text()
await browser.elementByCss('#revalidate-path-redirect').click()
await check(async () => {
const text = await browser.elementByCss('h1').text()
console.log('text', text)
return text && text.length > 0 ? text : 'failed'
}, /Multipart form data is not supported/)
const newRandomNumber = await browser
.elementByCss('#random-number')
.text()
const newJustPutIt = await browser.elementByCss('#justputit').text()
const newThankYouNext = await browser
.elementByCss('#thankyounext')
.text()
return newRandomNumber === randomNumber &&
justPutIt !== newJustPutIt &&
thankYouNext === newThankYouNext
? 'success'
: 'failure'
}, 'success')
})
})
}
......
'use server'
import { redirect } from 'next/navigation'
export async function inc(value) {
return value + 1
}
......@@ -11,3 +13,7 @@ export async function dec(value) {
export default async function (value) {
return value * 2
}
export async function redirectAction(path) {
redirect(path)
}
......@@ -2,11 +2,10 @@
import { useState } from 'react'
import double, { inc, dec } from './actions'
import double, { inc, dec, redirectAction } from './actions'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<h1>{count}</h1>
......@@ -37,6 +36,22 @@ export default function Counter() {
>
*2
</button>
<form>
<button
id="redirect"
formAction={() => redirectAction('/redirect-target')}
>
redirect
</button>
</form>
<form>
<button
id="redirect-external"
formAction={() => redirectAction('https://example.com')}
>
redirect external
</button>
</form>
</div>
)
}
'use server'
import { headers, cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export async function getCookie(name) {
return cookies().get(name)
......@@ -14,3 +15,8 @@ export async function setCookie(name, value) {
cookies().set(name, value)
return cookies().get(name)
}
export async function setCookieAndRedirect(name, value, path) {
cookies().set(name, value)
redirect(path)
}
import { getCookie, getHeader, setCookie } from './actions'
import UI from './ui'
import {
getCookie,
getHeader,
setCookie,
setCookieAndRedirect,
} from './actions'
import { validator } from './validator'
export default function Page() {
......@@ -9,6 +15,7 @@ export default function Page() {
getCookie={getCookie}
getHeader={getHeader}
setCookie={setCookie}
setCookieAndRedirect={setCookieAndRedirect}
getAuthedUppercase={validator(async (str) => {
'use server'
return prefix + ' ' + str.toUpperCase()
......
......@@ -6,6 +6,7 @@ export default function UI({
getCookie,
getHeader,
setCookie,
setCookieAndRedirect,
getAuthedUppercase,
}) {
const [result, setResult] = useState('')
......@@ -64,6 +65,19 @@ export default function UI({
>
getAuthedUppercase
</button>
<form>
<button
formAction={async () => {
await setCookieAndRedirect(
'redirect',
Math.random().toString(36).substring(7),
'/redirect-target'
)
}}
>
setCookieAndRedirect
</button>
</form>
</div>
)
}
......@@ -2,7 +2,10 @@ export default function RootLayout({ children }) {
return (
<html>
<head />
<body>{children}</body>
<body>
<div id="random-number">{Math.random()}</div>
{children}
</body>
</html>
)
}
import { cookies } from 'next/dist/client/components/headers'
export default function Page() {
const redirectCookie = cookies().get('redirect')
return (
<div>
<div id="redirected-cookie">
{redirectCookie ? redirectCookie.value : 'no-redirected-cookie'}
</div>
<div id="redirected">redirected</div>
</div>
)
}
import {
// unstable_cache,
revalidatePath,
revalidateTag,
} from 'next/cache'
import { redirect } from 'next/navigation'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page',
{
next: { revalidate: 360, tags: ['thankyounext'] },
}
).then((res) => res.text())
const data2 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a=b',
{
next: { revalidate: 360, tags: ['thankyounext', 'justputit'] },
}
).then((res) => res.text())
// TODO: make this work + add test
// const cachedData = await unstable_cache(
// async () => {
// const fetchedRandom = await fetch(
// 'https://next-data-api-endpoint.vercel.app/api/random'
// ).then((res) => res.json())
// return {
// now: Date.now(),
// random: Math.random(),
// fetchedRandom,
// }
// },
// ['random'],
// {
// tags: ['thankyounext'],
// }
// )()
return (
<>
<p>/revalidate</p>
<p>
{' '}
revalidate (tags: thankyounext): <span id="thankyounext">{data}</span>
</p>
<p>
revalidate (tags: thankyounext, justputit):{' '}
<span id="justputit">{data2}</span>
</p>
{/* <p>revalidate 10 (tags: thankyounext): {JSON.stringify(cachedData)}</p> */}
<form>
<button
id="revalidate-thankyounext"
formAction={async () => {
'use server'
revalidateTag('thankyounext')
}}
>
revalidate thankyounext
</button>
</form>
<form>
<button
id="revalidate-justputit"
formAction={async () => {
'use server'
revalidateTag('justputit')
}}
>
revalidate justputit
</button>
</form>
<form>
<button
id="revalidate-path"
formAction={async () => {
'use server'
revalidatePath('/revalidate')
}}
>
revalidate path
</button>
</form>
<form>
<button
id="revalidate-path-redirect"
formAction={async () => {
'use server'
revalidateTag('justputit')
redirect('/revalidate')
}}
>
revalidate justputit + redirect
</button>
</form>
<form>
<button
id="redirect"
formAction={async () => {
'use server'
redirect('/revalidate')
}}
>
redirect
</button>
</form>
</>
)
}
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