janglad - For Next JS users, how do you guys ha...
For Next JS users, how do you guys handle setting a global error map? I'm not sure what the most elegant solution is here.
.setErrorMap()
does what I want it do but it'd ideally run once before anything else on both server boot/before first render on the client.
Is it a bad idea to just call the function in my main layout (server side) and then have an empty client component above children there that also just calls it on every render (putting in a useEffect won't work as that runs after first render)4 Replies
Not in NextJS, but in the project at work we have this file:
The
shared/zod/locale.ts
file which is imported there is the one which sets up the global error map.
Then wherever we use zod, we import it from this shared file instead of directly from zod, meaning the errormap will always be set up.
Might be better solutions, but I find this fairly clean and maintainable. I tend to like doing this with most libraries. Wrap them up, set them up with project specific defaults, and only export the actual parts of the library we use to limit the API surface we expose ourselves to.This might indeed be the best solution, thank you
I played around with instrumentation (experimental Next JS feature that runs code before server boot), but somehow doesn't work for this. Not sure why.
ughh this doesn't completely work as I'd hoped. React hook form still uses the default errors
assume this is cause they're importing zod internally and that's done after the import for mine is evaluated
can solve by doing the same thing for the zodResolver as you showed above tho ofc
needs to be in a separate "use client" marked file tho cause apparently just importing it creates a context which you can't do on the server lol
It shouldn't matter where zodResolver imports zod from. The
locale.ts
file, or whatever it is that sets up that global error map just needs to be imported somewhere. In the case of Next app directory, and react-hook-form running on the client, you need to make sure that the locale is also set up on the client-side. It doesn't help to configure a global error map on the server, when that's thrown away and not passed on to the client.
In our case, we have crated wrappers for react-hook-form as well though, as useZodForm
and also implemented our own <ZodForm>
component, and they both import our shared/zod
, so then we're sure things are set up correctly everywhere.Yea I ended up doing something similar, thank you!