JSONB field and zod validation

I have a JSONB field with an explicit type

payload: jsonb("payload").$type<Record<string, unknown>>().notNull(),


and the correpsonding zod schema is correctly inferred as

schema: z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>


but I can give any value to schema and it doesn't cause a zod parsing error (eg "null", some array, some immediate values

is that expected? I thought it would enforce the type?

so for now I do a refinement like

        .refine(
          (payload) => {
            const parsed = z.record(z.string(), z.unknown()).safeParse(payload);
            return parsed.error === undefined;
          },
          {
            message:
              "Payload must be a JSON object {'key': value}, not an Array or an immediate value",
          },
        )


how are we supposed to ensure the JSONB fields are typed correctly with drizzle-zod?
Was this page helpful?