11 ms·
Zod 4
- 90s_dev 1y ago> TypeScript-first schema validation with static type inference Is there a comparison guide? Never heard of this before, but I used io-ts and ajv.
- cluckindan 1y agoBetween GraphQL and Zod, there really is no comparison. The latter feels clunky and superfluous by design when the former ecosystem can smoothly provide static TS typings without extra work or schema duplication.
- eknkc 1y agoAlso, I think teflon pans are much better than squids.
- lyu07282 1y agoSquid ink is black so are teflon pans, the latter feels clunky and superfluous by design when the former type of fruit can smoothly provide vitamins to vertically integrate with our stack.
- gejose 1y agoAh yes two totally different technologies - let's compare them like they're designed to solve the exact same problem
- cluckindan 1y agoGraphQL is a different animal, but I was only comparing the features Zod implements to those found in the GraphQL ecosystem.
- deleted 1y ago[deleted]
- neilpa 1y agoWe're currently evaluating both Zod and ArkType as a replacement for earlier JSON schema validations. The thing I can't get over with Zod is the syntax is _so_ different from defining TS types. Are there reasons to go with Zod over ArkType?
- CharlieDigital 1y agoYou might like Typia better. I recently put together a deck for this after some investigation: https://docs.google.com/presentation/d/1fToIKvR7dyvQS1AAtp4YuSwN6qi2kj_GBoIEJioWyTM/edit?usp=sharing https://docs.google.com/presentation/d/1fToIKvR7dyvQS1AAtp4Y...
- fkyoureadthedoc 1y agoOn the ArkType website they talk about speed and DX, but no mention of bundle size. I assume, and maybe this is an unfair assumption, that's because it's bad. I haven't come across ArkType until just now, but I was just checking out Valibot today because it's got a small bundle size.
- rafram 1y agohttps://bundlephobia.com/package/arktype@2.1.20 https://bundlephobia.com/package/arktype@2.1.20: 38.3 KB https://bundlephobia.com/package/zod@3.24.4 https://bundlephobia.com/package/zod@3.24.4: 64.3 KB https://bundlephobia.com/package/valibot@1.1.0 https://bundlephobia.com/package/valibot@1.1.0: 84.1 KB
- colinmcd 1y agoThese numbers don't reflect anything useful. This is the total size of the code in the package, most of which will be tree-shaken. In Zod's case, the package now contains three independent sub-libraries. I recommend plugging a script into bundlejs.com[0] to see bundle size numbers for a particular script [0] https://bundlejs.com https://bundlejs.com
- petesergeant 1y agoEveryone else is using Zod so the LLMs understand it well, there’s a big ecosystem, it’s unlikely to disappear overnight, and new hires may well already use it. It’s the boring solution.
- causal 1y agoZod is a lot better than some of the alternative solutions I've seen. That said, the need for this sort of explicit validation always felt like a failure of where modern web development has taken us. It's so frustrating how full-stack development requires so many ways of describing the same shapes: JS input validation, Swagger for API definition, server-side input validation, ORM for schema conformance, and TypeScript often requiring separate definitions on server and client side. It's so tedious.
- koolba 1y agoBut that’s the whole point of something like this. You do it once and dynamically generate everything else downstream. So change it once in the zod schema and it propagates with type checking through your entire app. The zod schema becomes the source of truth.
- worldsayshi 1y agoDoes zod really support that? What if the code base start out with a go backend and a TS/JS component is only added later? It would be nice if the source of truth was a bit more language agnostic.
- oxidant 1y agoBetter to use something like OpenApi and generate your zod schema using it.
- crabmusket 1y agoAnd thus is born the 15th IDL for cross language API calls...
- esafak 1y agoDoes it? I don't use Zod on my JVM backend. How would I? In addition to using OpenAPI, I generate TS interfaces from my data classes in a Gradle task.
- 1y ago
- devin 1y agoSeeing an announcement for a new version of some typescript library I've never heard of shoot to the top of the front page makes me feel extremely out of touch with mainstream dev.
- esafak 1y agoWhat do you use for validation in TS? Anyone who deals with data should be validating/parsing it.
- 90s_dev 1y agoconst cached = new Map<string, Function>() export function as<T>(o: any, path: string, as: (o: any) => T | undefined) { try { let fn = cached.get(path) if (!fn) cached.set(path, fn = new Function('o', `return o.${path}`)) const v = fn(o) return as(v) as T | undefined } catch (e) { return undefined } } as.number = (o: any) => (typeof o === 'number' ? o : undefined) as.string = (o: any) => (typeof o === 'string' ? o : undefined) as.boolean = (o: any) => (typeof o === 'boolean' ? o : undefined) as.numbers = (len = 0) => (o: any) => (o instanceof Array && o.length >= len && o.every(c => typeof c === 'number') ? o : undefined) as.strings = (len = 0) => (o: any) => (o instanceof Array && o.length >= len && o.every(c => typeof c === 'string') ? o : undefined) const size = as(usrConfig, 'sys.size', as.numbers(2)) const fontpath = as(usrConfig, 'sys.font', as.string)
- rafram 1y agoGreat if that's the only validation you need, but I can't imagine using it in a real app, and there are some obvious bugs (e.g. never use `instanceof Array`).
- 90s_dev 1y agoArray.isArray isn't needed when you know your array isn't going to be deserialized e.g. via MessagePort. What other supposed bugs? And yes I'm aware this doesn't have a huge API surface. That's the whole point. If I already have a JSON object, I can reach into it and get either what I ask for or nothing. In many real world cases, this is enough.
- varbhat 1y agoI am not an expert here but I had a thought that JSON-Schema might be a good choice because since it's schema based, i can implement the validators in Non-Typescript languages too. https://ajv.js.org https://ajv.js.org is one such JSON Schema library. How does zod compare to this?
- rafram 1y agoWell, Zod isn't just for validating JSON. It supports validating objects that can't be represented in JSON without transformation (dates, class instances, and so on). You can also use it as your JSON transformer if you want to - you can write your schema so it accepts strings, validates them as ISO date strings, and outputs Date objects, for instance.
- nozzlegear 1y ago> Well, Zod isn't just for validating JSON. It supports validating objects that can't be represented in JSON without transformation (dates, class instances, and so on). Thanks, this was the missing piece for me. I'd been thinking about using Zod for an old client's Node codebase, but I'd only need it to validate the shape of json objects received by http endpoints. Zod was looking like overkill, but I know it's popular so I wasn't sure what I was missing.
- 0x62 1y agoZod 4 supports converting a Zod schema to JSON-Schema (natively, this has always been possible with 3rd-party libs). One key difference is preprocessing/refine. With Zod, you can provide a callback before running validation, which is super useful and can't be represented in JSON. This comes in handy more often than you'd think - e.g converting MM/DD/YYYY to DD/MM/YYYY before validating as date.
- silverwind 1y agoDoes it support the other way around too? I'd live to ditch AJV.
- 1y ago
- ar-nelson 1y agoObligatory shameless plug whenever Zod is posted: if you want similar, but much more minimal schema validation at runtime, with a JSON representation, try Spartan Schema: https://github.com/ar-nelson/spartan-schema https://github.com/ar-nelson/spartan-schema
- jilles 1y agoWhen I see a repository with many files "updated 4 years ago" I'm usually inclined to think it's abandoned.
- ashwinsundar 1y agoOr the code is done and doesn’t need to be iterated on continuously?
- jzig 1y agoThen say so in the readme :)
- ashwinsundar 1y agoHard to please everyone
- johnfn 1y agoI'm curious if anyone here can answer a question I've wondered about for a long time. I've heard Zod might be in the right ballpark, but from reading the documentation, I'm not sure how I would go about it. Say I have a type returned by the server that might have more sophisticated types than the server API can represent. For instance, api/:postid/author returns a User, but it could either be a normal User or an anonymous User, in which case fields like `username`, `location`, etc come back null. So in this case I might want to use a discriminated union to represent my User object. And other objects coming back from other endpoints might also need some type alterations done to them as well. For instance, a User might sometimes have Post[] on them, and if the Post is from a moderator, it might have special attributes, etc - another discriminated union. In the past, I've written functions like normalizeUser() and normalizePost() to solve this, but this quickly becomes really messy. Since different endpoints return different subsets of the User/Post model, I would end up writing like 5 different versions of normalizePost for each endpoint, which seems like a mess. How do people solve this problem?
- peab 1y agoEither Unions, or optional fields
- adpirz 1y agoIt's hard to unpack without knowing more about the use case, but adding discriminant properties (e.g. "user_type") to all the types in the union can make it easier to handle the general and specific case. E.g. if (user.user_type === 'authenticated') { // do something with user.name because the type system knows we have that now }
- probabletrain 1y agoIn an ideal world you'd have one source of truth for what the shape of a User could be (which may well be a discriminated union of User and AnonymousUser or similar). Without fullstack TS this could look something like: (for a Python backend) Pydantic models+union for the various shapes of `User`, and then OpenAPI/GraphQL schema generation+codegen for the TS client.
- 1y ago
- satvikpendem 1y agoZod 4 looks good but even with their latest improvements, ArkType is still an order of magnitude faster. Sometimes for the sake of backward and syntax compatibility, it is difficult to make something much faster than a fully greenfield newer library. We recently did an analysis of all these types of tools for our project and decided to go with ArkType for partially this reason, the other was TypeScript ergonomics felt nicer.
- dangoodmanUT 1y agoArkType is a nightmare to use, zod is nice to use
- lhnz 1y agoOut of interest, why is it a nightmare to use? I've always been worried about how overly clever the approach is, does it have problems?
- atonse 1y agoI was looking at all their speed metrics, and can you explain to me where the speed makes a difference? We only use zod to validate forms, so I keep thinking "how does this matter?" Are people maybe using it to validate high throughput API input messages or something like that, where performance may matter more?
- satvikpendem 1y agoYes, we use it to validate the API responses from the backend (as well as type validation on the backend itself from any frontend POST requests), and especially on the client side, speed and bundle size is very important.
- yhprum 1y agoDoes arktype not come with a larger bundle size than zod? That was the reason I was shying away from it at the moment, especially with the bundle size reductions with zod 4 as well [1] https://www.reddit.com/r/typescript/comments/1i3ogwi/announcing_arktype_20_validate_100x_faster_with/m7pdcdy/ https://www.reddit.com/r/typescript/comments/1i3ogwi/announc...
- indigovole 1y agoWith yet another exciting new release of something reaching the top of HN, I would just like to urge devs to put a description of the project they're actually releasing and a link to the page describing the project in the release announcement. These announcements could be a valuable touchpoint for you to reach a whole new audience, but I can't remember a single one that starts with something like "exciting new release of NAME, the X that does Y for users of Z. Check out the project home page at https:// https:// for more." Quite often, the release announcement is a dead end that can't even take me to the project! In this case, the only link is a tiny octocat in the lower left-hand corner, AFAICS.
- 8s2ngy 1y agoCongratulations to the Zod team on the new release. At the risk of sounding overtly negative, I can't help but shudder when I think about the number of breaking changes outlined in the migration guide. For projects that rely heavily on Zod, it feels like a daunting task ahead—one that will demand a lot of developer attention and time to navigate. Having maintained a few frontend projects that are 4-5 years old at work, I really empathize with them. In my experience, large React projects often depend on a multitude of libraries, and when each one rolls out substantial changes—sometimes with barely any documentation—it can quickly become overwhelming. This is honestly one of my least favorite aspects of working with JavaScript. It just feels like a constant uphill battle to keep everything in sync and functioning smoothly.
- koakuma-chan 1y ago> For projects that rely heavily on Zod, it feels like a daunting task ahead—one that will demand a lot of developer attention and time to navigate. Or just use an LLM.
- camgunz 1y agoAnd then pick through all the LLM's mistakes.
- rvnx 1y agoAsk another LLM to pick for you
- owebmaster 1y agobetter yet: use an LLM to generate a subset of Zod that is fit for the project
- cscheid 1y agoThis is the kind of task that LLMs are precisely terrible at; there isn't an abundance of Zod 4 examples, and the LLM will sure as shit will give you _something_ you are now by definition ill-equipped to assess. I'm confident about this assessment because I maintain a large-ish piece of software and perenially have to decipher user reports of hallucinated LLM syntax for new features.
- rafram 1y ago> To simplify the migration process both for users and Zod's ecosystem of associated libraries, Zod 4 is being published alongside Zod 3 as part of the zod@3.25 release. [...] import Zod 4 from the "/v4" subpath npm is an absolute disaster of a dependency management system. Peer dependencies are so broken that they had to make v4 pretend it's v3.
- fhd2 1y agoI feel like both Node.js and NPM were initially vibe coded before LLMs existed. Just a quick hack, kind of, that got hugely popular somewhat by accident. Edit: Thinking about it, that's the origin story of JavaScript as well, so rather fitting.
- derN3rd 1y agoWe've been using zod 4 beta already with great improvements but due to our huge codebase not being able to handle the required moduleResolution settings, we cannot upgrade... They could at least also publish it as a major version without the legacy layer EDIT: I've just seen the reason described here: https://github.com/colinhacks/zod/issues/4371 https://github.com/colinhacks/zod/issues/4371 TLDR: He doesn't want to trigger a "version bump avalanche" across the ecosystem. (Which I believe, wouldn't happen as they could still backport fixes and support the v3 for a time, as they do it right now)
- gejose 1y ago> Peer dependencies are so broken that they had to make v4 pretend it's v3 I'm not sure this is the right conclusion here. I think zod v4 is being included within v3 so consumers can migrate over incrementally. I.e refactor all usages, one by one to `import ... from 'zod/v4'`, and once that's done, upgrade to v4 entirely.
- revskill 1y agoMind blowing.
- mac9 1y agoThe little animation that highlights what section you are reading currently is beautiful
- johnisgood 1y agoWhat animation? I actually do not see it.
- yhprum 1y agoThis is a feature of Fumadocs that the site uses! [1] https://fumadocs.dev/ https://fumadocs.dev/
- jasonthorsness 1y agoBut how is the below possible - doesn't it need to include most of the TypeScript compiler? Does it compile the type definitions to some kind of validation structure (like how a compiled regex works) and then use just that? - Zero external dependencies - Works in Node.js and all modern browsers - Tiny: 2kb core bundle (gzipped)
- _tqr3 1y agoThe TypeScript compiler is only needed during development, the compiled JavaScript code contains no TypeScript-specific logic. Zod’s validation is entirely JavaScript-based, relying on simple checks (e.g., typeof, regexes, comparisons). Also, the 2kb bundle just for the zod/v4-mini package, the full zod/v4 package is quite large.
- hdjrudni 1y ago5.36kB is not "quite large". It's pretty reasonable, esp. if you're only running it on the server.
- Aeyxen 1y agoI think Zod uses JIT compilation via `new Function`, rather than including the entire TypeScript compiler. This method allows for concise validation logic, executing only what’s necessary at runtime.
- _tqr3 1y agoStill no hapi support?
- h1fra 1y agoImpressive results, we need some deep dive on the performance improvements!
- labadal 1y agoI just got started working Zod into a new project. This could not have happened at a better time. I would have needed to change so much ot migrate to v4 based on what I'm seeing.
- nikolay 1y agoZod and the way to define schemas with it has been one of the reasons I didn't want to touch TypeScript as it's becoming more prevalent!
- aduffy 1y agoSeeing v4-mini reminds me of an LLM. I can only assume the next major release will be zod-3.9-medium-high
- TheFlashBold 1y agoOr maybe 3.8-q4_K_M for a quantized version
- dankobgd 1y agoi would use it if there was just 1 normal zod lib not like how it is now: zod and zod mini and who knows what. I rather use arktype or valibot if i am in browser only.
- sroussey 1y agoHopefully someone can compare Zod4 to TypeBox. Last I looked, the nice thing about TypeBox was that is _was_ JsonSchema just typed which was nice for interoperability.
- hdjrudni 1y agoI was using TypeBox but switched to Zod. I like TypeBox but I found I don't actually need my schema to be a JSON Schema and the one time I did want a JSON Schema it was hard to get actual JSON back out of TypeBox. The thing I like about Zod is the "refinements" and "transforms" and the new "overwrite" in Zod 4 was just what I wanted. TypeBox does have a transform (https://github.com/sinclairzx81/typebox?tab=readme-ov-file#types-transform https://github.com/sinclairzx81/typebox?tab=readme-ov-file#t...) but you can't transform and then apply more validations and then maybe another transform, etc. For example, I like to trim strings before checking length.
- baalimago 1y agoI read this, and I find myself not wanting to migrate since I know that LLMs can't generate Zod 4 syntax yet.
- punkpeye 1y agoShocked by the negativity around this. I tested early versions of zod v4 and liked the new API, but was very concerned about what will be the migration path. I was even going to suggest to publish under a new package name. But the author's approach is ingenious. It allows for someone like me to start adopting v4 immediately without waiting for every dependency to update. Well done!
- hombre_fatal 1y agoYeah, it's a nice route. There's no way I could afford to do an all or nothing migration for something like validation.
- colinmcd 1y agoAuthor here, AMA! Regarding the versioning: I wrote a fairly detailed writeup here[0] for those who are interested in the reasons for this approach. Ultimately npm is not designed to handle the situation Zod finds itself in. Zod is subject to a bunch of constraints that virtually no other libraries are subject to. Namely, the are dozens or hundreds of libraries that directly import interfaces/classes from Zod and use them in their own public-facing API. Since these libraries are directly coupled to Zod, they would need to publish a new major version whenever Zod does. That's ultimately reasonable in isolation, but in Zod's case it would trigger a "version avalanche" would just be painful for everyone involved. Selfishly, I suspect it would result in a huge swath of the ecosystem pinning on v3 forever. The approach I ended up using is analogous to what Golang does. In essence a given package never publishes new breaking versions: they just add a new subpath when a new breaking release is made. In the TypeScript ecosystem, this means libraries can configure a single peer dependency on zod@^3.25.0 and support both versions simultaneously by importing what they need from "zod/v3" and "zod/v4". It provides a nice opt-in incremental upgrade path for end-users of Zod too. [0] https://github.com/colinhacks/zod/issues/4371 https://github.com/colinhacks/zod/issues/4371
- miohtama 1y agoThe path of least short term pain is often the best path. Everyone old in Python ecosystem remembers the Python 2/3 migration madness.
- elbajo 1y agoFirst thank you for the hard work, many of my local hacks will go away with the new features! As a convenience and mostly avoid typos in form names I use my own version of https://github.com/raflymln/zod-key-parser https://github.com/raflymln/zod-key-parser. I've been surprised something like this hasn't been implemented directly in the library. Curious if you think this is out of scope for Zod or just something you haven't gotten around to implement? (Here are discussions around it: https://github.com/colinhacks/zod/discussions/2134 https://github.com/colinhacks/zod/discussions/2134)
- colinmcd 1y ago
- deleted 1y ago[deleted]
- __natty__ 1y agoGreat job! I love support of json conversion you built-in. However, I find top level string bad choice as it was more verbose before, to have them under string() namespace.
- bobbyraduloff 1y agogreat job on zod. it’s an incredible library. also really excited about the locale errors. finally I can push the zod errors directly to the frontend. would love to take responsibility for the BG locale.
- msukkarieh 1y agoWe've been using zod for our open source tool and are loving it! Will definitely try to migrate over to v4 soon, thanks for the project!
- CGamesPlay 1y agoOne decision that seems dubious to me is the zod/v4-mini import. I suspect that this will actually increase bundle sizes across the ecosystem. The docs specifically say "zod/v4 is still recommended for the majority of use cases", so application developers will use it. Library authors will think to themselves, "but I want to enable my library to be used by those with uncommonly strict bundle size requirements", and so will use that. The net result is that both zod/v4 and zod/v4-mini will be included in the application bundle. I guess this could be mostly avoided if zod/v4 actually a wrapper around zod/v4-mini. Is that the case?
- LinusU 1y agoLibrary authors should only import from `core`, which is used by both v4 and v4-mini. ref: https://zod.dev/library-authors?id=how-to-support-zod-and-zod-mini-simultaneously https://zod.dev/library-authors?id=how-to-support-zod-and-zo...
- CGamesPlay 1y agoGlad to see that this was also considered. I’m curious why they went with a third API, though.
- s-mon 1y agoWho else here is going to the Zod meetup tonight?
- LMMojo 1y agoAll that text. So, so much text and not one single (maybe there was, but I fell asleep), not one single "Let me tell you what Zod is" paragraph. Lots of "Zod 4 is better than Zod 3" and "Here's what we pulled back, out, in, from Zod 2".
- gitroom 1y ago[dead]
- MobiusHorizons 1y agoThe website fails to load with a javascript error in Safari. `SyntaxError: Invalid regular expression: invalid group specifier name`
- lioeters 1y agoLooks like this feature is not yet supported in Safari. Lookbehind in JS regular expressions - https://caniuse.com/js-regexp-lookbehind https://caniuse.com/js-regexp-lookbehind
- mrwww 1y agoDefining schemas in zod and using z.infer<> to get my types is just lovely, thank you!
- _1tem 1y agoAs a full stack dev that runs their own SaaS with thousands of users in production, sometimes I get a very pleasant reminder of how many problems I am blissfully unaware of just because I decided not to build an SPA or use JS frontend frameworks. It never occurred to me that I need such a thing as Zod/ArkType - first time hearing of it, and I have no use for it. It boggles my mind how much effort and complexity and tooling goes into building an SPA. Entire classes of problems simply don't exist if you choose not to build an SPA. Meanwhile, I use the browser as designed: with full page reloads, backend development only, and occasional reactivity using a backend-only framework like Laravel Livewire. Everything is so simple: from access control to validation to state management. And yes, my app is fast, reactive, modern, SEO friendly, and serves thousands of users in production.
- giorgioz 1y agoWhat's your SaaS? I would like to check out your use case that allowed you to build a great product without SPA.
- _1tem 1y agoBasecamp and Hey are $100m+ software companies that use Ruby on Rails without an SPA.
- tauchunfall 1y agoYes, and it actually works. I use something like htmx or fixi [1] for my frontends of side-projects. Alternatively, I could also use laravel livewire, I even argue you could use them for large-scale projects like ERP systems. I even re-build small parts of a large ERP system including the design system implemention using htmx. No need for react or similar things, if you know HTML and CSS well and are a bit disciplined. But once you don't use ORMs or have a non-monolithic architecture, you need something to validate your schema. [1] https://github.com/bigskysoftware/fixi https://github.com/bigskysoftware/fixi
- SebastianKra 1y agoWell how do you do server-side validation? Because now I have the impression that you're just defensively writing a bunch of if-statements. Or worse, you rely on html client-side form validation only.
- slackfan 1y agohmmm. Zod on Zed?
- pipallweek 1y agoThe versioning approach here is a really interesting compromise — especially in the npm ecosystem where breaking changes ripple out so painfully through transitive dependencies. From a developer ergonomics standpoint though, the shift to zod/v4 imports will definitely create some friction. For teams with IDEs auto-importing from 'zod' and linters enforcing import styles, it might introduce subtle DX issues until workflows are adjusted. That said, the strategy does seem to prioritize ecosystem stability over short-term convenience, which is fair. Would love to see better tooling (maybe even IDE plugins or codemods) to help projects transition cleanly. Really appreciate the thoughtful design behind all of this.
- assimpleaspossi 1y agoWow! This is great!!! What is it?
- bdangubic 1y agoZod, version 4
- assimpleaspossi 1y agoWhich tells me less than what the link to the web site tells me.
- enbugger 1y agoThe library pretty much remained unusable garbage without documentation comments. I have no idea why it became so popular and why this release is named "stable" when there is even no 4.0.0.