vars schema on Cli.create() to enable typed variables. Middleware sets them with c.set(), and both middleware and command handlers read them via c.var.
Basic Usage
How It Works
- Declare the schema — pass
varstoCli.create()with a Zod object schema - Set values in middleware — call
c.set(key, value)to populate variables - Read in handlers — access
c.var.keyin middleware or command handlers
Variable Defaults
Use.default() for variables that don’t need middleware:
Middleware Example
Authentication
Request Context
Type Inference
Thevars schema flows through generics to middleware and command handlers:
Middleware Type Hints
For external middleware, use themiddleware helper with type parameters:
Environment + Variables
Combine CLI-levelenv with vars for environment variables plus middleware state:
Typing External Middleware
For middleware defined outside your CLI, pass bothvars and env as type parameters:
Per-Command Middleware
Per-command middleware inherits the CLI’svars schema:
Best Practices
Do
- Use
varsfor state set by middleware (user, session, etc.) - Use
.default()for static configuration (timeouts, flags) - Use
z.custom<T>()for complex types - Type external middleware with
middleware<typeof cli.vars, typeof cli.env>()
Don’t
- Don’t use
varsfor arguments or options — useargsandoptionsschemas - Don’t use
varsfor environment variables — useenvschema - Don’t mutate
c.vardirectly — always usec.set()
Related
- See Middleware for composable before/after hooks
- See Environment Variables for
envschema

