Skip to content

Commit fee786a

Browse files
authored
[Fizz] Recover from errors thrown by progressive enhancement form generation (#28611)
This a follow up to #28564. It's alternative to #28609 which takes #28610 into account. It used to be possible to return JSX from an action with `useActionState`. ```js async function action(errors, payload) { "use server"; try { ... } catch (x) { return <div>Error message</div>; } } ``` ```js const [errors, formAction] = useActionState(action); return <div>{errors}</div>; ``` Returning JSX from an action is itself not anything problematic. It's that it also has to return the previous state to the action reducer again that's the problem. When this happens we accidentally could serialize an Element back to the server. I fixed this in #28564 so it's now blocked if you don't have a temporary reference set. However, you can't have that for the progressive enhancement case. The reply is eagerly encoded as part of the SSR render. Typically you wouldn't have these in the initial state so the common case is that they show up after the first POST back that yields an error and it's only in the no-JS case where this happens so it's hard to discover. As noted in #28609 there's a security implication with allowing elements to be sent across this kind of payload, so we can't just make it work. When an error happens during SSR our general policy is to try to recover on the client instead. After all, SSR is mainly a perf optimization in React terms and it's not primarily intended for a no JS solution. This PR takes the approach that if we fail to generate the progressive enhancement payload. I.e. if the serialization of previous state / closures throw. Then we fallback to the replaying semantics just client actions instead which will succeed. The effect of this is that this pattern mostly just works: - First render in the typical case doesn't have any JSX in it so it just renders a progressive enhanced form. - If JS fails to hydrate or you click early we do a form POST. If that hits an error and it tries to render it using JSX, then the new page will render successfully - however this time with a Replaying form instead. - If you try to submit the form again it'll have to be using JS. Meaning if you use JSX as the error return value of form state and you make a first attempt that fails, then no JS won't work because either the first or second attempt has to hydrate. We have ideas for potentially optimizing away serializing unused arguments like if you don't actually use previous state which would also solve it but it wouldn't cover all cases such as if it was deeply nested in complex state. Another approach that I considered was to poison the prev state if you passed an element back but let it through to the action but if you try to render the poisoned value, it wouldn't work. The downside of this is when to error. Because in the progressive enhancement case it wouldn't error early but when you actually try to invoke it at which point it would be too late to fallback to client replaying. It would probably have to always error even on the client which is unfortunate since this mostly just works as long as it hydrates.
1 parent 72e02a8 commit fee786a

File tree

2 files changed

+109
-11
lines changed

2 files changed

+109
-11
lines changed

packages/react-dom-bindings/src/server/ReactFizzConfigDOM.js

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,14 +1045,43 @@ function pushAdditionalFormField(
10451045

10461046
function pushAdditionalFormFields(
10471047
target: Array<Chunk | PrecomputedChunk>,
1048-
formData: null | FormData,
1048+
formData: void | null | FormData,
10491049
) {
1050-
if (formData !== null) {
1050+
if (formData != null) {
10511051
// $FlowFixMe[prop-missing]: FormData has forEach.
10521052
formData.forEach(pushAdditionalFormField, target);
10531053
}
10541054
}
10551055

1056+
function getCustomFormFields(
1057+
resumableState: ResumableState,
1058+
formAction: any,
1059+
): null | ReactCustomFormAction {
1060+
const customAction = formAction.$$FORM_ACTION;
1061+
if (typeof customAction === 'function') {
1062+
const prefix = makeFormFieldPrefix(resumableState);
1063+
try {
1064+
return formAction.$$FORM_ACTION(prefix);
1065+
} catch (x) {
1066+
if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
1067+
// Rethrow suspense.
1068+
throw x;
1069+
}
1070+
// If we fail to encode the form action for progressive enhancement for some reason,
1071+
// fallback to trying replaying on the client instead of failing the page. It might
1072+
// work there.
1073+
if (__DEV__) {
1074+
// TODO: Should this be some kind of recoverable error?
1075+
console.error(
1076+
'Failed to serialize an action for progressive enhancement:\n%s',
1077+
x,
1078+
);
1079+
}
1080+
}
1081+
}
1082+
return null;
1083+
}
1084+
10561085
function pushFormActionAttribute(
10571086
target: Array<Chunk | PrecomputedChunk>,
10581087
resumableState: ResumableState,
@@ -1062,7 +1091,7 @@ function pushFormActionAttribute(
10621091
formMethod: any,
10631092
formTarget: any,
10641093
name: any,
1065-
): null | FormData {
1094+
): void | null | FormData {
10661095
let formData = null;
10671096
if (enableFormActions && typeof formAction === 'function') {
10681097
// Function form actions cannot control the form properties
@@ -1092,12 +1121,10 @@ function pushFormActionAttribute(
10921121
);
10931122
}
10941123
}
1095-
const customAction: ReactCustomFormAction = formAction.$$FORM_ACTION;
1096-
if (typeof customAction === 'function') {
1124+
const customFields = getCustomFormFields(resumableState, formAction);
1125+
if (customFields !== null) {
10971126
// This action has a custom progressive enhancement form that can submit the form
10981127
// back to the server if it's invoked before hydration. Such as a Server Action.
1099-
const prefix = makeFormFieldPrefix(resumableState);
1100-
const customFields = formAction.$$FORM_ACTION(prefix);
11011128
name = customFields.name;
11021129
formAction = customFields.action || '';
11031130
formEncType = customFields.encType;
@@ -1882,12 +1909,10 @@ function pushStartForm(
18821909
);
18831910
}
18841911
}
1885-
const customAction: ReactCustomFormAction = formAction.$$FORM_ACTION;
1886-
if (typeof customAction === 'function') {
1912+
const customFields = getCustomFormFields(resumableState, formAction);
1913+
if (customFields !== null) {
18871914
// This action has a custom progressive enhancement form that can submit the form
18881915
// back to the server if it's invoked before hydration. Such as a Server Action.
1889-
const prefix = makeFormFieldPrefix(resumableState);
1890-
const customFields = formAction.$$FORM_ACTION(prefix);
18911916
formAction = customFields.action || '';
18921917
formEncType = customFields.encType;
18931918
formMethod = customFields.method;

packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMForm-test.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -897,4 +897,77 @@ describe('ReactFlightDOMForm', () => {
897897

898898
expect(form.action).toBe('http://localhost/permalink');
899899
});
900+
901+
// @gate enableFormActions
902+
// @gate enableAsyncActions
903+
it('useFormState can return JSX state during MPA form submission', async () => {
904+
const serverAction = serverExports(
905+
async function action(prevState, formData) {
906+
return <div>error message</div>;
907+
},
908+
);
909+
910+
function Form({action}) {
911+
const [errorMsg, dispatch] = useFormState(action, null);
912+
return <form action={dispatch}>{errorMsg}</form>;
913+
}
914+
915+
const FormRef = await clientExports(Form);
916+
917+
const rscStream = ReactServerDOMServer.renderToReadableStream(
918+
<FormRef action={serverAction} />,
919+
webpackMap,
920+
);
921+
const response = ReactServerDOMClient.createFromReadableStream(rscStream, {
922+
ssrManifest: {
923+
moduleMap: null,
924+
moduleLoading: null,
925+
},
926+
});
927+
const ssrStream = await ReactDOMServer.renderToReadableStream(response);
928+
await readIntoContainer(ssrStream);
929+
930+
const form1 = container.getElementsByTagName('form')[0];
931+
expect(form1.textContent).toBe('');
932+
933+
async function submitTheForm() {
934+
const form = container.getElementsByTagName('form')[0];
935+
const {formState} = await submit(form);
936+
937+
// Simulate an MPA form submission by resetting the container and
938+
// rendering again.
939+
container.innerHTML = '';
940+
941+
const postbackRscStream = ReactServerDOMServer.renderToReadableStream(
942+
<FormRef action={serverAction} />,
943+
webpackMap,
944+
);
945+
const postbackResponse = ReactServerDOMClient.createFromReadableStream(
946+
postbackRscStream,
947+
{
948+
ssrManifest: {
949+
moduleMap: null,
950+
moduleLoading: null,
951+
},
952+
},
953+
);
954+
const postbackSsrStream = await ReactDOMServer.renderToReadableStream(
955+
postbackResponse,
956+
{formState: formState},
957+
);
958+
await readIntoContainer(postbackSsrStream);
959+
}
960+
961+
await expect(submitTheForm).toErrorDev(
962+
'Warning: Failed to serialize an action for progressive enhancement:\n' +
963+
'Error: React Element cannot be passed to Server Functions from the Client without a temporary reference set. Pass a TemporaryReferenceSet to the options.\n' +
964+
' [<div/>]\n' +
965+
' ^^^^^^',
966+
);
967+
968+
// The error message was returned as JSX.
969+
const form2 = container.getElementsByTagName('form')[0];
970+
expect(form2.textContent).toBe('error message');
971+
expect(form2.firstChild.tagName).toBe('DIV');
972+
});
900973
});

0 commit comments

Comments
 (0)