Unverified Commit 2dc45422 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

add unstable_isUnrecognizedActionError (#78933)

`unstable_isUnrecognizedActionError` is a new API that lets user code
check if a server action call failed because the action id wasn't
recognized by the server. This usually happens as a result of version
skew between client and server.

Example usage:

 ```ts
 try {
   await myServerAction();
 } catch (err) {
   if (unstable_isUnrecognizedActionError(err)) {
     // The client is from a different deployment than the server.
     // Reloading the page will fix this mismatch.
     window.alert("Please refresh the page and try again");
     return;
   }
 }
 ```
It can also be used to create a special error boundary, like we do in
the tests added here.

Note that this API is not a complete solution to this problem, as it
doesn't allow handling failures for MPA actions (sent without JS). We
might add a more complete API for this in the future to address that.
parent 95d7db7d
......@@ -624,6 +624,7 @@ impl ReactServerComponentValidator {
"useRouter",
"useServerInsertedHTML",
"ServerInsertedHTMLContext",
"unstable_isUnrecognizedActionError",
],
),
("next/link", vec!["useLinkStatus"]),
......
......@@ -54,6 +54,7 @@ fn is_error_class_name(name: &str) -> bool {
|| name == "SerializableError"
|| name == "StaticGenBailoutError"
|| name == "TimeoutError"
|| name == "UnrecognizedActionError"
|| name == "Warning"
}
......
......@@ -773,5 +773,6 @@
"772": "FetchStrategy.PPRRuntime should never be used when `experimental.clientSegmentCache` is disabled",
"773": "Missing workStore in createPrerenderParamsForClientSegment",
"774": "Route %s used %s outside of a Server Component. This is not allowed.",
"775": "Node.js instrumentation extensions should not be loaded in the Edge runtime."
"775": "Node.js instrumentation extensions should not be loaded in the Edge runtime.",
"776": "`unstable_isUnrecognizedActionError` can only be used on the client."
}
......@@ -26,6 +26,12 @@ class ReadonlyURLSearchParams extends URLSearchParams {
}
}
export function unstable_isUnrecognizedActionError(): boolean {
throw new Error(
'`unstable_isUnrecognizedActionError` can only be used on the client.'
)
}
export { redirect, permanentRedirect } from './redirect'
export { RedirectType } from './redirect-error'
export { notFound } from './not-found'
......
......@@ -272,6 +272,8 @@ export function useSelectedLayoutSegment(
: selectedLayoutSegment
}
export { unstable_isUnrecognizedActionError } from './unrecognized-action-error'
// Shared components APIs
export {
notFound,
......
......@@ -12,6 +12,7 @@ import {
NEXT_URL,
RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers'
import { UnrecognizedActionError } from '../../unrecognized-action-error'
// TODO: Explicitly import from client.browser
// eslint-disable-next-line import/no-extraneous-dependencies
......@@ -114,7 +115,7 @@ async function fetchServerAction(
// Handle server actions that the server didn't recognize.
const unrecognizedActionHeader = res.headers.get(NEXT_ACTION_NOT_FOUND_HEADER)
if (unrecognizedActionHeader === '1') {
throw new Error(
throw new UnrecognizedActionError(
`Server Action "${actionId}" was not found on the server. \nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
)
}
......
export class UnrecognizedActionError extends Error {
constructor(...args: ConstructorParameters<typeof Error>) {
super(...args)
this.name = 'UnrecognizedActionError'
}
}
/**
* Check whether a server action call failed because the server action was not recognized by the server.
* This can happen if the client and the server are not from the same deployment.
*
* Example usage:
* ```ts
* try {
* await myServerAction();
* } catch (err) {
* if (unstable_isUnrecognizedActionError(err)) {
* // The client is from a different deployment than the server.
* // Reloading the page will fix this mismatch.
* window.alert("Please refresh the page and try again");
* return;
* }
* }
* ```
* */
export function unstable_isUnrecognizedActionError(
error: unknown
): error is UnrecognizedActionError {
return !!(
error &&
typeof error === 'object' &&
error instanceof UnrecognizedActionError
)
}
'use client'
import * as React from 'react'
import { useActionState } from 'react'
import { unstable_isUnrecognizedActionError as isUnrecognizedActionError } from 'next/navigation'
export function FormWithArg<T>({
action,
......@@ -41,12 +42,16 @@ export function Form({
)
}
export class ErrorBoundary extends React.Component<{
export class UnrecognizedActionBoundary extends React.Component<{
children: React.ReactNode
}> {
state = { error: null }
static getDerivedStateFromError(error) {
return { error }
if (isUnrecognizedActionError(error)) {
return { error }
} else {
throw error
}
}
render() {
if (this.state.error) {
......
import * as React from 'react'
import { FormWithArg, Form, ErrorBoundary } from './client'
import { FormWithArg, Form, UnrecognizedActionBoundary } from './client'
const action = async (...args: any[]) => {
'use server'
......@@ -14,12 +14,12 @@ export default function Page() {
return (
<div>
<div>
<ErrorBoundary>
<UnrecognizedActionBoundary>
<Form action={action} />
</ErrorBoundary>
</UnrecognizedActionBoundary>
</div>
<div>
<ErrorBoundary>
<UnrecognizedActionBoundary>
<FormWithArg
action={action}
id="form-simple-argument"
......@@ -27,10 +27,10 @@ export default function Page() {
>
Submit client form with simple argument
</FormWithArg>
</ErrorBoundary>
</UnrecognizedActionBoundary>
</div>
<div>
<ErrorBoundary>
<UnrecognizedActionBoundary>
<FormWithArg
action={action}
id="form-complex-argument"
......@@ -38,7 +38,7 @@ export default function Page() {
>
Submit client form with complex argument
</FormWithArg>
</ErrorBoundary>
</UnrecognizedActionBoundary>
</div>
</div>
)
......
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