Redirecting when validateSearch fails
I'm trying to determine what the best practice is for the following, I've read through the docs and existing questions, and apologies if I've missed something obvious, but I can't seem to find an answer to this:
I have a route component which requires an email address as a search param. I'm using a zod schema to validate this at the route level via
validateSearch
, so that the search params type will always be { email: string }
(i.e. email is never null
or an invalid email address).
The schema is using strict validation with no default or fallback value, so an error will be thrown if it fails to parse. Ideally, I would like to redirect to a different page if the validation fails, without ever rendering the route component (so that if the route component does get rendered, it can be safely assumed that the search param is valid), but I'm unsure about the best way to achieve this.
If I throw a redirect
in the validateSearch
function itself, then this seems to be seen as a validation error and causes the error component to be triggered. If I don't throw the redirect
, and instead just invoke it and don't return anything from validateSearch
, then the return type of validateSearch
now includes undefined
as a possibility.
I've tried calling redirect
in the beforeLoad
function for the route, though it seems that the search validation occurs before this, and since an error is thrown by the search validation, it will also trigger the error component first.
I've considered setting a fallback value for the email address in the schema (i.e. set email to null
if validation fails), then redirecting from the route component based on whether it is null
, but I feel like this would better be handled at the route definition level rather than the component.
I feel that I might be missing something straightforward, and I'd like to follow what the best practices are as much as possible.
Some guidance or suggestions for this would be greatly appreciated!2 Replies
flat-fuchsia•15mo ago
Maybe try checking if the error type is that of a zod error in the
errorComponent
for that route and use <Navigate to="....." replace />
modern-teal•11mo ago
I solved this problem like:
This catches zod search param validation errors