In Zod 4, why is calling z.config(z.locales.fr()) inside a request handler a fragile way to localise validation messages per user, and what would you do instead?
answer
- one config for the whole process
- lowest rung of the chain
- messages fixed during parse
- scope the map to one call
- or translate codes at render
basics
~20 sz.config writes one process-wide config, so a per-request locale leaks into other requests and can race with async parses. Instead pass a per-parse error map for the user's language, or translate issue codes at render time.
solid answer
~50 s`z.config` assigns into a single global config object, shared on `globalThis` even across separately loaded copies of Zod, and the locale is stored there as the lowest-priority error map. Setting it per request mutates state every request sees: a request that does not set it inherits whichever language the previous caller chose, and with `safeParseAsync` another request can switch the language before your issues get their messages, since messages are written during the parse. Hard-coded schema strings outrank the locale anyway. Better options: pass the language's map to that call only, `schema.safeParse(body, { error: frMap })` with `frMap = z.locales.fr().localeError` built once; make schema `error` functions call a translation helper, which run at parse time; or keep issues language-neutral and translate at render time from `code` and its parameters. Calling `z.config` once at startup suits a single-language service or a browser tab.
code
typescript · 13 linesimport * as z from "zod";
const maps = {
en: z.locales.en().localeError,
fr: z.locales.fr().localeError,
};
const SignUp = z.object({ email: z.email(), password: z.string().min(8) });
export function validateSignUp(body: unknown, lang: keyof typeof maps) {
// Scoped to this call; the process-wide config is untouched.
return SignUp.safeParse(body, { error: maps[lang] });
}go deeper
Recall that z.config with a locale changes default messages for the whole program, not for one request.
Explain where the locale sits in the precedence chain, that messages are produced during the parse, and how a per-parse error map scopes a language to one call.
Show why per-request z.config fails under concurrency and async parsing, and pick between per-parse maps, translating error functions and render-time translation.
Decide where wording is owned across a shared client and server schema, since global config, schema text and render-time translation each fix a different team boundary.
## What z.config actually changes Zod 4 has one configuration object, read on every parse. `z.config(partial)` merges your settings into it with a plain assignment and returns it. The object is kept on `globalThis`, so that every copy of Zod in the process (an ES module build and a CommonJS build, or two bundles in a monorepo) observes the same settings. Two of its keys matter for messages: - **`customError`**: a global error map, consulted before the locale. - **`localeError`**: the locale's error map, the **lowest-priority** source of messages. A locale such as `z.locales.fr()` is a function that returns `{ localeError }`, so `z.config(z.locales.fr())` replaces the process-wide locale map. The `zod` package registers English when the first schema is constructed, unless a locale is already set. ## Why per-request switching is fragile Calling `z.config(z.locales.fr())` at the start of a request handler mutates shared state: - **Leakage**: any request that does not set a locale gets whichever language the last request chose. - **Interleaving**: messages are written when Zod finalises the issues, at the end of the parse. A synchronous `safeParse` called straight after `z.config` finishes before other code runs, but `safeParseAsync` (needed when a schema has asynchronous refinements) yields, and another request can switch the language in between. - **No effect on explicit text**: messages hard-coded on schemas or checks outrank the locale, so a French locale leaves an English `z.string("Required")` in English. The pattern can appear to work in development with one user and fail under concurrent load, which is the definition of fragile. ## Options that scope the language correctly | Approach | Where the language is chosen | Notes | |---|---|---| | Per-parse error map | the parse call | ranks above global and locale maps, below schema and check text | | Error functions on schemas that call a translation helper | at parse time, inside the map | the helper must know the current request's language | | Translate at render time | the consumer of the issues | issues stay language-neutral; uses `code` and parameters | | `z.config` once at startup | process start | right for one-language services and browser apps | **Per-parse map.** A locale's `localeError` is an ordinary error map, so it can be passed straight to one call: ```ts const maps = { en: z.locales.en().localeError, fr: z.locales.fr().localeError }; const result = schema.safeParse(body, { error: maps[lang] }); ``` Build the maps once rather than per request. This affects only that call and nothing global. **Translation inside error functions.** Because an `error` function runs during the parse, `z.string().min(5, { error: (iss) => t("too_short", iss) })` produces text in whatever language `t` resolves at that moment. A schema defined once at module load still yields per-request wording. **Render-time translation.** Zod's documentation suggests translating the issue itself: the `code` is the key and the issue's other properties are the interpolation values, as in `issues.map((iss) => t(iss.code, iss))`. The server can then return codes and parameters and let the client choose the words. (What the response body looks like on the wire is a separate API-design question.) ## Bundle size and loading Importing every locale is unnecessary when only a few are used. The documentation shows lazy loading with a dynamic `import()` of a locale module, which suits a browser app picking a language once. Bundlers differ in how well they tree-shake the `z.locales` namespace, and the docs note that esbuild cannot do so with a default or named `z` import. ## The browser is different In a browser app, one runtime serves one user, so the global config is effectively per-user state: - calling `z.config(locale)` when the user picks a language is reasonable; - messages already attached to existing issues stay in the old language, because they were written during an earlier parse, so re-validate the form after switching; - a schema shared with the server still carries any hard-coded strings it has, in whatever language they were written. ## A decision checklist 1. Is there one language per process, or one user per runtime (a browser)? Then `z.config(locale)` once at startup is fine. 2. Do requests carry different languages? Keep `z.config` fixed and scope the language per call or per render. 3. Do shared schemas carry hard-coded strings? They will not translate through any map; move them to checks with functions or remove them. 4. Do clients need to format messages themselves? Return codes and parameters, and treat Zod's `message` as a default only. The underlying point is that the locale is global configuration, not per-request context, and Zod gives you narrower tools for the per-request case.
- In Zod 4, why might a per-parse French map still produce some English messages?Text written on a schema or a check outranks the per-parse map, so any literal English string in a shared schema survives. Only issues whose schema and check define no `error`, or whose error function returns `undefined`, reach the per-parse map.
- Is z.config(z.locales.de()) at startup safe in a single-language service?Yes. Set once before handling traffic, the global locale is just configuration: every parse reads the same map and nothing mutates it later. The fragility comes only from changing it while requests run, or from expecting it to override text hard-coded on schemas.
- z.config settings apply only to the module or request that called it.
- A locale overrides messages hard-coded on schemas and checks.
- Translating Zod messages requires one schema copy per language.
- Messages are fixed when the schema is defined, so language cannot vary per parse.
- Switching the global locale and resetting it afterwards is safe under async parsing.
Assumes Zod 4; the locales API, set through z.config, was introduced in Zod 4.