skip to content

In Zod 4, you add an async .refine() that checks whether a sign-up username is already taken, and every caller already uses safeParseAsync. What can still go wrong?

level: seniorimportance: should knowfreq 40%

answer

  1. a check that returns a promise
  2. the async parse methods
  3. a plain Error, not ZodError
  4. continuable issues still run it
  5. rejections escape the refinement

basics

~20 s

In Zod 4, the lookup still runs after continuable failures such as a too-short name, unless that check sets abort true or the refinement uses when. A rejected lookup escapes as an exception, not an issue, and the check is only a pre-check; the store's uniqueness rule is the real guarantee.

solid answer

~50 s

`.refine(async (name) => !(await isUsernameTaken(name)), { error: "That username is taken" })` is legal, but now every caller must use `parseAsync()` or `safeParseAsync()`. A synchronous `parse()` or `safeParse()` throws a plain `Error`, "Encountered Promise during synchronous parse. Use .parseAsync() instead.", the moment the check returns a promise; `safeParse()` does not catch it. The lookup runs whenever no non-continuable issue came first, so a too-short name still triggers a query unless the length check has `abort: true` or the refinement uses `when`. A wrong-type input skips the lookup, which is why a synchronous test with bad input can pass while real input throws. Return falsy for a taken name, but let infrastructure failures reject: Zod does not catch thrown errors, so a database outage rejects `safeParseAsync()` instead of becoming an issue. The lookup is also only a pre-check; the store's uniqueness rule is the real guarantee.

code

typescript · 18 lines
typescript
import * as z from "zod";

declare function isUsernameTaken(name: string): Promise<boolean>;

const Username = z
  .string()
  .min(3, { error: "At least 3 characters", abort: true })
  .refine(async (name) => !(await isUsernameTaken(name)), {
    error: "That username is taken",
  });

const SignUp = z.object({ username: Username, password: z.string().min(12) });

async function handle(body: unknown) {
  const result = await SignUp.safeParseAsync(body); // correct
  // SignUp.safeParse(body); // throws: "Encountered Promise during synchronous parse. Use .parseAsync() instead."
  return result;
}

go deeper

for a junior

Recall that an async refinement means using parseAsync or safeParseAsync, and that the synchronous methods throw instead.

for a middle

Explain why the thrown error is not a ZodError, why safeParse cannot catch it, and how abort: true keeps the lookup from running on short names.

for a senior

Diagnose why tests pass with synchronous parse while production throws, and separate a taken name from a failed lookup so outages never look like user errors.

for a principal

Decide where database-backed checks live: inside shared schemas, in a server-only extension, or in the service layer behind the store's own uniqueness rule.

## Writing the refinement `.refine()` accepts an async function. It resolves to a verdict exactly like a synchronous refinement: truthy passes, falsy adds a `"custom"` issue with your `error` message. For a username that must not already exist: ```ts const Username = z .string() .min(3, { error: "At least 3 characters", abort: true }) .refine(async (name) => !(await isUsernameTaken(name)), { error: "That username is taken", }); ``` `isUsernameTaken` stands for your own data-access function. Nothing else about the schema changes, but adding the `async` keyword changes how every caller must parse it. ## The parse call it forces - **You must parse with `parseAsync()` or `safeParseAsync()`.** These run the schema with async enabled and await any promise a check returns. - **A synchronous `parse()` or `safeParse()` throws** as soon as a check returns a promise. The thrown value is a plain `Error` with the message "Encountered Promise during synchronous parse. Use .parseAsync() instead.", not a `ZodError`. - **`safeParse()` does not protect you.** It catches validation issues, not this error, so the exception escapes it too. - **The requirement is contagious.** Any object, array or union containing this field now needs the async methods, wherever it is parsed. ## When the lookup runs and when it is skipped The refinement sits in the string schema's list of checks, which run in order: 1. If the value is not a string at all, the type check fails with a non-continuable issue and no check runs, so no lookup happens. 2. A failed `.min(3)` is **continuable by default**, so the lookup would still run on `"ab"` and spend a database query on a name that is already invalid. 3. Marking the length check `abort: true` makes its failure non-continuable, which skips the lookup for short names. 4. For finer control, the refinement's `when` option takes a function of the parse payload and returns whether to run. That ordering also explains a confusing test result. A test that feeds a number to a synchronous `parse()` passes, because the type failure skips the async check and no promise ever appears; a real username of valid length makes the same call throw. ## Failures inside the lookup Zod's own documentation says refinement functions should never throw, because thrown errors are not caught. - **A taken name is a verdict**: return falsy, and the user gets "That username is taken" as a normal issue. - **A database outage is not a verdict.** If `isUsernameTaken` rejects, `safeParseAsync()` rejects with that same error instead of resolving to a failure, and your request handler must deal with it as an infrastructure problem. - **Do not swallow the error by returning `false`.** That tells a user their name is taken when the truth is that nobody knows. | Input | Under `safeParse()` | Under `safeParseAsync()` | |---|---|---| | `42` (not a string) | Failure, no lookup | Failure, no lookup | | `"ab"` with `abort: true` on min | Failure, no lookup | Failure, no lookup | | `"ana"`, free | Throws the async error | Success | | `"ana"`, taken | Throws the async error | Failure, custom issue | | `"ana"`, database down | Throws the async error | Promise rejects | ## Cost and correctness - **One query per parse.** Every request that reaches the field pays for the lookup, including requests that fail other fields, because field checks run independently. - **It is a pre-check, not a guarantee.** Two sign-ups can both pass the lookup before either writes, so the store's own uniqueness rule still has to back it up. - **It ties the schema to the server.** A schema that needs a database call cannot also be used unchanged in a browser bundle, so teams often keep the async rule in a server-only extension of a shared base schema. - **Async transforms follow the same rules**: a `.transform()` with an async function also forces the async parse methods. ## Mistakes to avoid - Adding an async refinement and leaving synchronous `parse()` calls elsewhere in the codebase. - Expecting `safeParse()` to turn the async error into a failed result. - Letting length or format failures trigger a lookup on input that is already invalid. - Returning `false` when the lookup itself failed, which turns an outage into a misleading message. How to choose between throwing and result-returning parse calls in general is covered in the lesson on parsing at the boundary; this lesson keeps what an async refinement changes.

  • Why can a unit test call parse() on this schema without failing, while production throws?
    The test probably sends input that fails the type check, such as a number. That issue is non-continuable, so the async refinement is skipped, no promise appears, and the synchronous parse returns normally. Production sends a real string of valid length, the refinement runs, returns a promise, and the synchronous call throws. Test with valid input, and use `safeParseAsync()` everywhere this schema is parsed.
  • Should the refinement catch a database error and return false?
    No. Returning `false` reports "That username is taken" for a name nobody checked, which misleads the user and hides an outage. Let the rejection propagate: `safeParseAsync()` then rejects, and the request handler can answer with a server-error response and log it. Zod documents that refinement functions should not throw because it does not catch errors, so infrastructure failures are yours to handle outside the schema.

  • Expects safeParse() to return a failed result when it meets an async refinement.
  • Believes a failed min length always stops the async lookup from running.
  • Returns false from the lookup when the database call itself fails.
  • Treats the async uniqueness refinement as a guarantee against duplicate usernames.
  • Thinks an async refinement only affects the field it is attached to.