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[] = [ ...@@ -88,8 +88,8 @@ const babelIncludeRegexes: RegExp[] = [
const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/ const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/
const staticGenerationAsyncStorageRegex = const asyncStoragesRegex =
/next[\\/]dist[\\/]client[\\/]components[\\/]static-generation-async-storage/ /next[\\/]dist[\\/]client[\\/]components[\\/](static-generation-async-storage|action-async-storage)/
const mainFieldsPerCompiler: Record<CompilerNameValues, string[]> = { const mainFieldsPerCompiler: Record<CompilerNameValues, string[]> = {
[COMPILER_NAMES.server]: ['main', 'module'], [COMPILER_NAMES.server]: ['main', 'module'],
...@@ -1841,10 +1841,7 @@ export default async function getBaseWebpackConfig( ...@@ -1841,10 +1841,7 @@ export default async function getBaseWebpackConfig(
and: [ and: [
codeCondition.test, codeCondition.test,
{ {
not: [ not: [optOutBundlingPackageRegex, asyncStoragesRegex],
optOutBundlingPackageRegex,
staticGenerationAsyncStorageRegex,
],
}, },
], ],
}, },
...@@ -1866,7 +1863,7 @@ export default async function getBaseWebpackConfig( ...@@ -1866,7 +1863,7 @@ export default async function getBaseWebpackConfig(
// Make sure that AsyncLocalStorage module instance is shared between server and client // Make sure that AsyncLocalStorage module instance is shared between server and client
// layers. // layers.
layer: WEBPACK_LAYERS.shared, layer: WEBPACK_LAYERS.shared,
test: staticGenerationAsyncStorageRegex, test: asyncStoragesRegex,
}, },
] ]
: []), : []),
...@@ -1900,7 +1897,7 @@ export default async function getBaseWebpackConfig( ...@@ -1900,7 +1897,7 @@ export default async function getBaseWebpackConfig(
// Alias react for switching between default set and share subset. // Alias react for switching between default set and share subset.
oneOf: [ oneOf: [
{ {
exclude: [staticGenerationAsyncStorageRegex], exclude: [asyncStoragesRegex],
issuerLayer: { issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action], or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
}, },
...@@ -1974,7 +1971,7 @@ export default async function getBaseWebpackConfig( ...@@ -1974,7 +1971,7 @@ export default async function getBaseWebpackConfig(
issuerLayer: { issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action], or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
}, },
exclude: [staticGenerationAsyncStorageRegex], exclude: [asyncStoragesRegex],
use: swcLoaderForServerLayer, use: swcLoaderForServerLayer,
}, },
{ {
...@@ -1987,10 +1984,7 @@ export default async function getBaseWebpackConfig( ...@@ -1987,10 +1984,7 @@ export default async function getBaseWebpackConfig(
issuerLayer: { issuerLayer: {
or: [WEBPACK_LAYERS.client, WEBPACK_LAYERS.appClient], or: [WEBPACK_LAYERS.client, WEBPACK_LAYERS.appClient],
}, },
exclude: [ exclude: [asyncStoragesRegex, codeCondition.exclude],
staticGenerationAsyncStorageRegex,
codeCondition.exclude,
],
use: [ use: [
...(dev && isClient ...(dev && isClient
? [ ? [
......
// @ts-ignore import { getServerActionDispatcher } from './components/app-router'
// eslint-disable-next-line import/no-extraneous-dependencies
import { encodeReply } from 'react-server-dom-webpack/client'
export async function callServer(id: string, args: any[]) { export async function callServer(actionId: string, actionArgs: any[]) {
const actionId = id const actionDispatcher = getServerActionDispatcher()
// Fetching the current url with the action header. if (!actionDispatcher) {
// TODO: Refactor this to look up from a manifest. throw new Error('Invariant: missing action dispatcher.')
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())
} }
return (await res.json())[0] return new Promise((resolve, reject) => {
actionDispatcher({
actionId,
actionArgs,
resolve,
reject,
})
})
} }
...@@ -24,8 +24,12 @@ import { ...@@ -24,8 +24,12 @@ import {
ACTION_PREFETCH, ACTION_PREFETCH,
ACTION_REFRESH, ACTION_REFRESH,
ACTION_RESTORE, ACTION_RESTORE,
ACTION_SERVER_ACTION,
ACTION_SERVER_PATCH, ACTION_SERVER_PATCH,
PrefetchKind, PrefetchKind,
RouterChangeByServerResponse,
RouterNavigate,
ServerActionDispatcher,
} from './router-reducer/router-reducer-types' } from './router-reducer/router-reducer-types'
import { createHrefFromUrl } from './router-reducer/create-href-from-url' import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { import {
...@@ -53,6 +57,12 @@ let initialParallelRoutes: CacheNode['parallelRoutes'] = isServer ...@@ -53,6 +57,12 @@ let initialParallelRoutes: CacheNode['parallelRoutes'] = isServer
? null! ? null!
: new Map() : new Map()
let globalServerActionDispatcher = null as ServerActionDispatcher | null
export function getServerActionDispatcher() {
return globalServerActionDispatcher
}
export function urlToUrlWithoutFlightMarker(url: string): URL { export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin) const urlWithoutFlightParameters = new URL(url, location.origin)
// TODO-APP: handle .rsc for static export case // TODO-APP: handle .rsc for static export case
...@@ -170,7 +180,7 @@ function Router({ ...@@ -170,7 +180,7 @@ function Router({
/** /**
* Server response that only patches the cache and tree. * Server response that only patches the cache and tree.
*/ */
const changeByServerResponse = useCallback( const changeByServerResponse: RouterChangeByServerResponse = useCallback(
( (
previousTree: FlightRouterState, previousTree: FlightRouterState,
flightData: FlightData, flightData: FlightData,
...@@ -193,11 +203,8 @@ function Router({ ...@@ -193,11 +203,8 @@ function Router({
[dispatch] [dispatch]
) )
/** const navigate: RouterNavigate = useCallback(
* 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 = (
href: string, href: string,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean
...@@ -219,8 +226,31 @@ function Router({ ...@@ -219,8 +226,31 @@ function Router({
}, },
mutable: {}, 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 = { const routerInstance: AppRouterInstance = {
back: () => window.history.back(), back: () => window.history.back(),
forward: () => window.history.forward(), forward: () => window.history.forward(),
...@@ -297,13 +327,18 @@ function Router({ ...@@ -297,13 +327,18 @@ function Router({
} }
return routerInstance return routerInstance
}, [dispatch]) }, [dispatch, navigate])
// Add `window.nd` for debugging purposes. // Add `window.nd` for debugging purposes.
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router. // This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// @ts-ignore this is for debugging // @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. // When mpaNavigation flag is set do a hard navigation to the new url.
......
...@@ -2,7 +2,12 @@ ...@@ -2,7 +2,12 @@
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { AppRouterInstance } from '../../shared/lib/app-router-context' import { AppRouterInstance } from '../../shared/lib/app-router-context'
import { useRouter } from './navigation' import { useRouter } from './navigation'
import { getURLFromRedirectError, isRedirectError } from './redirect' import {
RedirectType,
getRedirectTypeFromError,
getURLFromRedirectError,
isRedirectError,
} from './redirect'
interface RedirectBoundaryProps { interface RedirectBoundaryProps {
router: AppRouterInstance router: AppRouterInstance
...@@ -12,8 +17,10 @@ interface RedirectBoundaryProps { ...@@ -12,8 +17,10 @@ interface RedirectBoundaryProps {
function HandleRedirect({ function HandleRedirect({
redirect, redirect,
reset, reset,
redirectType,
}: { }: {
redirect: string redirect: string
redirectType: RedirectType
reset: () => void reset: () => void
}) { }) {
const router = useRouter() const router = useRouter()
...@@ -21,38 +28,44 @@ function HandleRedirect({ ...@@ -21,38 +28,44 @@ function HandleRedirect({
useEffect(() => { useEffect(() => {
// @ts-ignore startTransition exists // @ts-ignore startTransition exists
React.startTransition(() => { React.startTransition(() => {
if (redirectType === RedirectType.push) {
router.push(redirect, {})
} else {
router.replace(redirect, {}) router.replace(redirect, {})
}
reset() reset()
}) })
}, [redirect, reset, router]) }, [redirect, redirectType, reset, router])
return null return null
} }
export class RedirectErrorBoundary extends React.Component< export class RedirectErrorBoundary extends React.Component<
RedirectBoundaryProps, RedirectBoundaryProps,
{ redirect: string | null } { redirect: string | null; redirectType: RedirectType | null }
> { > {
constructor(props: RedirectBoundaryProps) { constructor(props: RedirectBoundaryProps) {
super(props) super(props)
this.state = { redirect: null } this.state = { redirect: null, redirectType: null }
} }
static getDerivedStateFromError(error: any) { static getDerivedStateFromError(error: any) {
if (isRedirectError(error)) { if (isRedirectError(error)) {
const url = getURLFromRedirectError(error) const url = getURLFromRedirectError(error)
return { redirect: url } const redirectType = getRedirectTypeFromError(error)
return { redirect: url, redirectType }
} }
// Re-throw if error is not for redirect // Re-throw if error is not for redirect
throw error throw error
} }
render() { render() {
const redirect = this.state.redirect const { redirect, redirectType } = this.state
if (redirect !== null) { if (redirect !== null && redirectType !== null) {
return ( return (
<HandleRedirect <HandleRedirect
redirect={redirect} redirect={redirect}
redirectType={redirectType}
reset={() => this.setState({ redirect: null })} reset={() => this.setState({ redirect: null })}
/> />
) )
......
const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT' const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'
export enum RedirectType {
push = 'push',
replace = 'replace',
}
type RedirectError<U extends string> = Error & { 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 & { ...@@ -11,11 +28,11 @@ type RedirectError<U extends string> = Error & {
* *
* @param url the url to redirect to * @param url the url to redirect to
*/ */
export function redirect(url: string): never { export function redirect(
// eslint-disable-next-line no-throw-literal url: string,
const error = new Error(REDIRECT_ERROR_CODE) type: RedirectType = RedirectType.replace
;(error as RedirectError<typeof url>).digest = `${REDIRECT_ERROR_CODE};${url}` ): never {
throw error throw getRedirectError(url, type)
} }
/** /**
...@@ -28,10 +45,14 @@ export function redirect(url: string): never { ...@@ -28,10 +45,14 @@ export function redirect(url: string): never {
export function isRedirectError<U extends string>( export function isRedirectError<U extends string>(
error: any error: any
): error is RedirectError<U> { ): error is RedirectError<U> {
if (typeof error?.digest !== 'string') return false
const [errorCode, type, destination] = (error.digest as string).split(';', 3)
return ( return (
typeof error?.digest === 'string' && errorCode === REDIRECT_ERROR_CODE &&
error.digest.startsWith(REDIRECT_ERROR_CODE + ';') && (type === 'replace' || type === 'push') &&
error.digest.length > REDIRECT_ERROR_CODE.length + 1 typeof destination === 'string'
) )
} }
...@@ -45,11 +66,20 @@ export function isRedirectError<U extends string>( ...@@ -45,11 +66,20 @@ export function isRedirectError<U extends string>(
export function getURLFromRedirectError<U extends string>( export function getURLFromRedirectError<U extends string>(
error: RedirectError<U> error: RedirectError<U>
): U ): U
export function getURLFromRedirectError(error: any): string | null
export function getURLFromRedirectError(error: any): string | null { export function getURLFromRedirectError(error: any): string | null {
if (!isRedirectError(error)) return null if (!isRedirectError(error)) return null
// Slices off the beginning of the digest that contains the code and the // Slices off the beginning of the digest that contains the code and the
// separating ';'. // 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( ...@@ -140,7 +140,7 @@ export function navigateReducer(
) { ) {
const segments = pathname.split('/') const segments = pathname.split('/')
// TODO-APP: figure out something better for index pages // TODO-APP: figure out something better for index pages
segments.push('') segments.push('__PAGE__')
// Optimistic tree case. // Optimistic tree case.
// If the optimistic tree is deeper than the current state leave that deeper part out of the fetch // 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( ...@@ -165,7 +165,7 @@ export function navigateReducer(
// TODO-APP: re-evaluate if we need to strip the last segment // TODO-APP: re-evaluate if we need to strip the last segment
const optimisticFlightSegmentPath = segments const optimisticFlightSegmentPath = segments
.slice(1) .slice(1)
.map((segment) => ['children', segment === '' ? '__PAGE__' : segment]) .map((segment) => ['children', segment])
.flat() .flat()
// Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch. // 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' ...@@ -12,6 +12,19 @@ export const ACTION_RESTORE = 'restore'
export const ACTION_SERVER_PATCH = 'server-patch' export const ACTION_SERVER_PATCH = 'server-patch'
export const ACTION_PREFETCH = 'prefetch' export const ACTION_PREFETCH = 'prefetch'
export const ACTION_FAST_REFRESH = 'fast-refresh' 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 { export interface Mutable {
mpaNavigation?: boolean mpaNavigation?: boolean
...@@ -25,6 +38,12 @@ export interface Mutable { ...@@ -25,6 +38,12 @@ export interface Mutable {
hashFragment?: string hashFragment?: string
} }
export interface ServerActionMutable {
inFlightServerAction?: Promise<any> | null
serverActionApplied?: boolean
previousTree?: FlightRouterState
}
/** /**
* Refresh triggers a refresh of the full page data. * Refresh triggers a refresh of the full page data.
* - fetches the Flight data and fills subTreeData at the root of the cache. * - fetches the Flight data and fills subTreeData at the root of the cache.
...@@ -44,6 +63,24 @@ export interface FastRefreshAction { ...@@ -44,6 +63,24 @@ export interface FastRefreshAction {
origin: Location['origin'] 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`. * Navigate triggers a navigation to the provided url. It supports two types: `push` and `replace`.
* *
...@@ -224,4 +261,5 @@ export type ReducerActions = Readonly< ...@@ -224,4 +261,5 @@ export type ReducerActions = Readonly<
| ServerPatchAction | ServerPatchAction
| PrefetchAction | PrefetchAction
| FastRefreshAction | FastRefreshAction
| ServerActionAction
> >
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
ReducerState, ReducerState,
ReadonlyReducerState, ReadonlyReducerState,
ACTION_FAST_REFRESH, ACTION_FAST_REFRESH,
ACTION_SERVER_ACTION,
} from './router-reducer-types' } from './router-reducer-types'
import { navigateReducer } from './reducers/navigate-reducer' import { navigateReducer } from './reducers/navigate-reducer'
import { serverPatchReducer } from './reducers/server-patch-reducer' import { serverPatchReducer } from './reducers/server-patch-reducer'
...@@ -15,6 +16,7 @@ import { restoreReducer } from './reducers/restore-reducer' ...@@ -15,6 +16,7 @@ import { restoreReducer } from './reducers/restore-reducer'
import { refreshReducer } from './reducers/refresh-reducer' import { refreshReducer } from './reducers/refresh-reducer'
import { prefetchReducer } from './reducers/prefetch-reducer' import { prefetchReducer } from './reducers/prefetch-reducer'
import { fastRefreshReducer } from './reducers/fast-refresh-reducer' import { fastRefreshReducer } from './reducers/fast-refresh-reducer'
import { serverActionReducer } from './reducers/server-action-reducer'
/** /**
* Reducer that handles the app-router state updates. * Reducer that handles the app-router state updates.
...@@ -42,6 +44,9 @@ function clientReducer( ...@@ -42,6 +44,9 @@ function clientReducer(
case ACTION_PREFETCH: { case ACTION_PREFETCH: {
return prefetchReducer(state, action) return prefetchReducer(state, action)
} }
case ACTION_SERVER_ACTION: {
return serverActionReducer(state, action)
}
// This case should never be hit as dispatch is strongly typed. // This case should never be hit as dispatch is strongly typed.
default: default:
throw new Error('Unknown action') throw new Error('Unknown action')
......
...@@ -7,9 +7,9 @@ export interface StaticGenerationStore { ...@@ -7,9 +7,9 @@ export interface StaticGenerationStore {
readonly pathname: string readonly pathname: string
readonly originalPathname?: string readonly originalPathname?: string
readonly incrementalCache?: IncrementalCache readonly incrementalCache?: IncrementalCache
readonly isRevalidate?: boolean
readonly isOnDemandRevalidate?: boolean readonly isOnDemandRevalidate?: boolean
readonly isPrerendering?: boolean readonly isPrerendering?: boolean
readonly isRevalidate?: boolean
forceDynamic?: boolean forceDynamic?: boolean
fetchCache?: fetchCache?:
...@@ -28,6 +28,7 @@ export interface StaticGenerationStore { ...@@ -28,6 +28,7 @@ export interface StaticGenerationStore {
dynamicUsageStack?: string dynamicUsageStack?: string
nextFetchId?: number nextFetchId?: number
pathWasRevalidated?: boolean
tags?: string[] 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 { isNotFoundError } from '../../client/components/not-found'
import { import {
getURLFromRedirectError, getURLFromRedirectError,
isRedirectError, isRedirectError,
} from '../../client/components/redirect' } from '../../client/components/redirect'
import RenderResult from '../render-result' 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) { function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query) const searchParams = new URLSearchParams(query)
...@@ -18,18 +30,143 @@ function formDataFromSearchQueryString(query: string) { ...@@ -18,18 +30,143 @@ function formDataFromSearchQueryString(query: string) {
return formData 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({ export async function handleAction({
req, req,
res, res,
ComponentMod, ComponentMod,
pathname, pathname,
serverActionsManifest, serverActionsManifest,
generateFlight,
staticGenerationStore,
}: { }: {
req: IncomingMessage req: IncomingMessage
res: ServerResponse res: ServerResponse
ComponentMod: any ComponentMod: any
pathname: string pathname: string
serverActionsManifest: any serverActionsManifest: any
generateFlight: (options: {
actionResult: ActionResult
skipFlight: boolean
}) => Promise<RenderResult>
staticGenerationStore: StaticGenerationStore
}): Promise<undefined | RenderResult | 'not-found'> { }): Promise<undefined | RenderResult | 'not-found'> {
let actionId = req.headers[ACTION.toLowerCase()] as string let actionId = req.headers[ACTION.toLowerCase()] as string
const contentType = req.headers['content-type'] const contentType = req.headers['content-type']
...@@ -60,9 +197,11 @@ export async function handleAction({ ...@@ -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 { try {
await actionAsyncStorage.run({ isAction: true }, async () => { await actionAsyncStorage.run({ isAction: true }, async () => {
...@@ -145,38 +284,71 @@ export async function handleAction({ ...@@ -145,38 +284,71 @@ export async function handleAction({
ComponentMod.__next_app_webpack_require__(actionModId)[actionId] ComponentMod.__next_app_webpack_require__(actionModId)[actionId]
const returnVal = await actionHandler.apply(null, bound) const returnVal = await actionHandler.apply(null, bound)
const result = new ActionRenderResult(JSON.stringify([returnVal]))
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { 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 return actionResult
} }
} catch (err) { } catch (err) {
if (isRedirectError(err)) { if (isRedirectError(err)) {
if (isFetchAction || process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
throw new Error('Invariant: not implemented.') throw new Error('Invariant: not implemented.')
} }
const redirectUrl = getURLFromRedirectError(err) 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) 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)) { } else if (isNotFoundError(err)) {
if (isFetchAction) { if (isFetchAction) {
throw new Error('Invariant: not implemented.') throw new Error('Invariant: not implemented.')
} }
await Promise.all(staticGenerationStore.pendingRevalidates || [])
res.statusCode = 404 res.statusCode = 404
return 'not-found' return 'not-found'
} }
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 res.statusCode = 500
return new RenderResult( const rejectedPromise = Promise.reject(err)
(err as Error)?.message ?? 'Internal Server Error' 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 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 { IncomingMessage, ServerResponse } from 'http'
import type { import type {
ActionResult,
ChildProp, ChildProp,
DynamicParamTypesShort, DynamicParamTypesShort,
FlightData, FlightData,
...@@ -936,7 +937,10 @@ export async function renderToHTMLOrFlight( ...@@ -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()`. // 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. * 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. * 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,7 +1150,9 @@ export async function renderToHTMLOrFlight( ...@@ -1146,7 +1150,9 @@ export async function renderToHTMLOrFlight(
// Flight data that is going to be passed to the browser. // 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. // Currently a single item array but in the future multiple patches might be combined in a single request.
const flightData: FlightData = ( const flightData: FlightData | null = options?.skipFlight
? null
: (
await walkTreeWithFlightRouterState({ await walkTreeWithFlightRouterState({
createSegmentPath: (child) => child, createSegmentPath: (child) => child,
loaderTreeToFilter: loaderTree, loaderTreeToFilter: loaderTree,
...@@ -1178,7 +1184,7 @@ export async function renderToHTMLOrFlight( ...@@ -1178,7 +1184,7 @@ export async function renderToHTMLOrFlight(
// For app dir, use the bundled version of Fizz renderer (renderToReadableStream) // For app dir, use the bundled version of Fizz renderer (renderToReadableStream)
// which contains the subset React. // which contains the subset React.
const readable = ComponentMod.renderToReadableStream( const readable = ComponentMod.renderToReadableStream(
flightData, options ? [options.actionResult, flightData] : flightData,
clientReferenceManifest.clientModules, clientReferenceManifest.clientModules,
{ {
context: serverContexts, context: serverContexts,
...@@ -1551,7 +1557,10 @@ export async function renderToHTMLOrFlight( ...@@ -1551,7 +1557,10 @@ export async function renderToHTMLOrFlight(
ComponentMod, ComponentMod,
pathname: renderOpts.pathname, pathname: renderOpts.pathname,
serverActionsManifest, serverActionsManifest,
generateFlight,
staticGenerationStore,
}) })
if (actionRequestResult === 'not-found') { if (actionRequestResult === 'not-found') {
return new RenderResult(await bodyResult({ asNotFound: true })) return new RenderResult(await bodyResult({ asNotFound: true }))
} else if (actionRequestResult) { } else if (actionRequestResult) {
......
...@@ -100,6 +100,10 @@ export type FlightDataPath = ...@@ -100,6 +100,10 @@ export type FlightDataPath =
*/ */
export type FlightData = Array<FlightDataPath> | string export type FlightData = Array<FlightDataPath> | string
export type ActionResult = Promise<any>
export type ActionFlightData = [ActionResult, FlightData | null]
/** /**
* Property holding the current subTreeData. * Property holding the current subTreeData.
*/ */
......
...@@ -65,7 +65,7 @@ export async function sendRenderResult({ ...@@ -65,7 +65,7 @@ export async function sendRenderResult({
const payload = result.isDynamic() ? null : await result.toUnchunkedString() const payload = result.isDynamic() ? null : await result.toUnchunkedString()
if (payload) { if (payload !== null) {
const etag = generateEtags ? generateETag(payload) : undefined const etag = generateEtags ? generateETag(payload) : undefined
if (sendEtagResponse(req, res, etag)) { if (sendEtagResponse(req, res, etag)) {
return return
...@@ -97,7 +97,7 @@ export async function sendRenderResult({ ...@@ -97,7 +97,7 @@ export async function sendRenderResult({
if (req.method === 'HEAD') { if (req.method === 'HEAD') {
res.end(null) res.end(null)
} else if (payload) { } else if (payload !== null) {
res.end(payload) res.end(payload)
} else { } else {
await result.pipe(res) await result.pipe(res)
......
...@@ -25,4 +25,7 @@ export function revalidateTag(tag: string) { ...@@ -25,4 +25,7 @@ export function revalidateTag(tag: string) {
console.error(`revalidateTag failed for ${tag}`, err) console.error(`revalidateTag failed for ${tag}`, err)
}) })
) )
// TODO: only revalidate if the path matches
store.pathWasRevalidated = true
} }
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-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( createNextDescribe(
'app-dir action handling', 'app-dir action handling',
...@@ -119,9 +123,12 @@ createNextDescribe( ...@@ -119,9 +123,12 @@ createNextDescribe(
await browser.elementByCss('#authed').click() await browser.elementByCss('#authed').click()
await check(() => { await check(
() => {
return browser.elementByCss('h1').text() return browser.elementByCss('h1').text()
}, 'Error: Unauthorized request') },
isNextDev ? 'Error: Unauthorized request' : GENERIC_RSC_ERROR
)
await await browser.eval(`document.cookie = 'auth=1'`) await await browser.eval(`document.cookie = 'auth=1'`)
...@@ -205,11 +212,120 @@ createNextDescribe( ...@@ -205,11 +212,120 @@ createNextDescribe(
await await browser.eval(`document.cookie = 'auth=0'`) await await browser.eval(`document.cookie = 'auth=0'`)
await browser.elementByCss('#authed').click() await browser.elementByCss('#authed').click()
await check(async () => { await check(
async () => {
const text = await browser.elementByCss('h1').text() const text = await browser.elementByCss('h1').text()
console.log('text', text) console.log('text', text)
return text && text.length > 0 ? text : 'failed' return text && text.length > 0 ? text : 'failed'
}, /Multipart form data is not supported/) },
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 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' 'use server'
import { redirect } from 'next/navigation'
export async function inc(value) { export async function inc(value) {
return value + 1 return value + 1
} }
...@@ -11,3 +13,7 @@ export async function dec(value) { ...@@ -11,3 +13,7 @@ export async function dec(value) {
export default async function (value) { export default async function (value) {
return value * 2 return value * 2
} }
export async function redirectAction(path) {
redirect(path)
}
...@@ -2,11 +2,10 @@ ...@@ -2,11 +2,10 @@
import { useState } from 'react' import { useState } from 'react'
import double, { inc, dec } from './actions' import double, { inc, dec, redirectAction } from './actions'
export default function Counter() { export default function Counter() {
const [count, setCount] = useState(0) const [count, setCount] = useState(0)
return ( return (
<div> <div>
<h1>{count}</h1> <h1>{count}</h1>
...@@ -37,6 +36,22 @@ export default function Counter() { ...@@ -37,6 +36,22 @@ export default function Counter() {
> >
*2 *2
</button> </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> </div>
) )
} }
'use server' 'use server'
import { headers, cookies } from 'next/headers' import { headers, cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export async function getCookie(name) { export async function getCookie(name) {
return cookies().get(name) return cookies().get(name)
...@@ -14,3 +15,8 @@ export async function setCookie(name, value) { ...@@ -14,3 +15,8 @@ export async function setCookie(name, value) {
cookies().set(name, value) cookies().set(name, value)
return cookies().get(name) 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 UI from './ui'
import {
getCookie,
getHeader,
setCookie,
setCookieAndRedirect,
} from './actions'
import { validator } from './validator' import { validator } from './validator'
export default function Page() { export default function Page() {
...@@ -9,6 +15,7 @@ export default function Page() { ...@@ -9,6 +15,7 @@ export default function Page() {
getCookie={getCookie} getCookie={getCookie}
getHeader={getHeader} getHeader={getHeader}
setCookie={setCookie} setCookie={setCookie}
setCookieAndRedirect={setCookieAndRedirect}
getAuthedUppercase={validator(async (str) => { getAuthedUppercase={validator(async (str) => {
'use server' 'use server'
return prefix + ' ' + str.toUpperCase() return prefix + ' ' + str.toUpperCase()
......
...@@ -6,6 +6,7 @@ export default function UI({ ...@@ -6,6 +6,7 @@ export default function UI({
getCookie, getCookie,
getHeader, getHeader,
setCookie, setCookie,
setCookieAndRedirect,
getAuthedUppercase, getAuthedUppercase,
}) { }) {
const [result, setResult] = useState('') const [result, setResult] = useState('')
...@@ -64,6 +65,19 @@ export default function UI({ ...@@ -64,6 +65,19 @@ export default function UI({
> >
getAuthedUppercase getAuthedUppercase
</button> </button>
<form>
<button
formAction={async () => {
await setCookieAndRedirect(
'redirect',
Math.random().toString(36).substring(7),
'/redirect-target'
)
}}
>
setCookieAndRedirect
</button>
</form>
</div> </div>
) )
} }
...@@ -2,7 +2,10 @@ export default function RootLayout({ children }) { ...@@ -2,7 +2,10 @@ export default function RootLayout({ children }) {
return ( return (
<html> <html>
<head /> <head />
<body>{children}</body> <body>
<div id="random-number">{Math.random()}</div>
{children}
</body>
</html> </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