colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
31.74k stars 1.1k forks source link

safeParse not working server sider with z.union() : Error: Attempted to call indexOf() from the server but indexOf is on the client. #3570

Open arnaudpfu opened 3 weeks ago

arnaudpfu commented 3 weeks ago

I am working on a next js app with the directory page system. I have a folder called [[...options]], which enable to get url segments in the url, more details about that here

I would like parse the string[] containing the segments with zod server side.

export const VIEW_OPTIONS = ['day', 'week', 'month', 'year'] as const;

type ViewOption = (typeof VIEW_OPTIONS)[number];
type Segments = ['booking', ViewOption, number, number, number] | [ViewOption, number, number, number];

const calendarOptionsSchema = z.union([
    z.tuple([z.literal('booking'), z.enum(VIEW_OPTIONS), z.number(), z.number(), z.number()]),
    z.tuple([z.enum(VIEW_OPTIONS), z.number(), z.number(), z.number()]),
    z.undefined(),
]);

const extractSegments = (options: Segments) => {
    if (!calendarOptionsSchema.safeParse(options).success) {
        // redirect to 404 page
        notFound();

    }
    // other stuff here
}

I get this issue :

Screenshot 2024-06-13 at 10 48 38

I looked on the internet, I have see nothing about this issue. If you have an idea/an explanation, you are welcome. :)

m10rten commented 1 week ago

Hi, do you still have this issue with the latest Next.js version?