versace - hey!I am currently investigating wh...
hey!
I am currently investigating what the best approach for using header validation through zod would be in regards to key case sensitivity. i'm currently in a situation where I need to have support for all headers to be supported regardless of how the casing looks when sent in from the request. any suggestions?
Solution:Jump to solution
Do you need to preserve the case of the incoming headers? You could transform them at runtime with
.toLowerCase()
and then build your schema on the lowercased keys.6 Replies
oh, that's a good one I haven't seen before!
I don't love it but it seems fine.
you could also use a case-insensitive regex that you build a runtime like:
I like this even less, but at least you get a
ZodString
instead of a ZodPipeline
interesting, the way it works for us today, is that we define the full object/schema of which headers exist, and then parse it as the first action in the request parsing flow.
the problem here is that the keys are by default sensitive inside of z.object, how would your solutions be applied here?
Headers are always
Record
-like structures, right? Always Record<string, string>
, so you could use z.record
with this custom string schema as the key schema. But, looking at your implementation, you want to make key-specific assertions, so that won't help much.Solution
Do you need to preserve the case of the incoming headers? You could transform them at runtime with
.toLowerCase()
and then build your schema on the lowercased keys.I guess for a record-like structure, you'd actually want to transform the keys to lowercase when parsing rather than just checking against lowercase, that way the object you get back on the other end is already normalized to lowercase.
Might be able to take some inspiration from zod-form-data (see https://github.com/airjp73/rvf/blob/main/packages/zod-form-data/src/helpers.ts) and build a preprocess pipeline for turning
Header
objects into plain objects.we decided to go the route of just lower casing the whole header object that is retrieved from the request, it didn't seem like any other option had good code maintenance experience.
thanks for your suggestions!