auto-form icon indicating copy to clipboard operation
auto-form copied to clipboard

Issue with Next.js and Autoform: Use of FormProvider in Server Components

Open baptisthecht opened this issue 1 year ago • 4 comments

When using Next.js, integrating Autoform causes crashes due to the import of FormProvider (from react-hook-form) within a server component.

Temporary Solution I had to manually add "use client" at the top of autoform/utils.ts and autoform/AutoForm.tsx files to resolve the issue.

Explanation Next.js defaults to server components, but contexts like FormProvider cannot be used in server components. Changing these components to client components by adding "use client" fixed the issue.

baptisthecht avatar Nov 04 '24 18:11 baptisthecht

Can you expand why it crashes? I use Nextjs with AutoForm (version from month ago but this was also based on react-hook-form) and it generally works with Nextjs 13, 14, and 15. The only issue I found was that because AutoForm does Zod validation on client side, if you wish to re-use the same Zod schema on the server-side you need to create a copy and have one schema with "use client" and another without it (for server side). Aide from that (very annoying) issue - I didn't experience any other issues with Nextjs and AutoForm.

moltco avatar Nov 04 '24 18:11 moltco

I'm not sure I can explain it in more detail — I encountered the error on my first attempt, and resolved it by adding "use client".

It seems clear to me that the form should be handled on the client side since it uses a context. You’re likely not experiencing the issue because your page or component calling AutoForm may be already marked as "use client".

After analyzing it further, I found that when using AutoForm as a server component, the imports from react-hook-form are loaded from index.react-server.esm.mjs instead of index.mjs. This causes an import error with FormProvider, as index.react-server.esm.mjs doesn't include FormProvider (since it’s intended for server components). Next.js defaults to this file instead of index.mjs when react-hook-form is used within a server component, which leads to the import error.

baptisthecht avatar Nov 04 '24 19:11 baptisthecht

It also doesn't work in Remix at all for probably the same reason.

monobyte avatar Nov 25 '24 07:11 monobyte

As described at https://autoform.vantezzen.io/docs/react/getting-started#nextjs-and-rsc, AutoForm is intended to be used in Client-side component since there had been problems with serializing zod schemas otherwise and handling of callbacks.

I'll see if I can maybe mark AutoForm itself with "use client" or if serialization problems have been fixed since then.

vantezzen avatar Nov 25 '24 09:11 vantezzen