Core API Methods
Suvidha usesCtxRequest
which extends the standard Express.js Request
object with a context
property,
for accessing request-specific data added by middlewares.
Suvidha(handlers: Handlers)
Suvidha(handlers: Handlers)
Main class for creating a new instance of Suvidha; requires a Handlers instance.
Handlers
Handlers
Refer to Handlers for more details.
.body(schema: ZodType)
.body(schema: ZodType)
.use(middleware)
.use(middleware)
Purpose
Builds request context through chainable middleware. Each call merges new properties into the context while preserving type safety. Any exceptions thrown will be handled byonErr
handler.Key Characteristics
Key Characteristics
- Order-Sensitive: Middleware executes in the order of declaration.
- Type Accumulation: Each middleware’s return type merges with previous context.
- Immutable Context: Each middleware gets current context in
Readonly
wrapper to prevent mutations. - Early Termination: Middleware can end response with
res.send()
.
Merging is the same as using the
...
spread operator, new_ctx = { ...current_ctx, ...ctx }
Middleware Signature
Example
Type Safety
.handler(fn)
.handler(fn)
.next()
.next()
Acts as an Express.js middleware. It executes the configured Suvidha middleware functions (both validation via
.body()
, .query()
, .params()
and custom logic via .use()
) in the order they are defined. After successful execution of these middlewares, .next()
calls the next middleware in the Express.js chain using the express’ next()
function.It’s like handler()
but with request handler as express’ next()
function.Example
The execution order of middlewares is the same as the order of declaration.Execution order is
query
-> middyA
-> middyB
-> params
-> handler
.Usage
Data Validation
Validate the request body using Zod schemas.Writing Middlewares
middlewares takeCtxRequest
and Response
as input arguments and return Context | Promise<Context>
.
Loosely Coupled Business Logic
Handles responses usingonComplete
and onErr
when using Suvidha
with Handlers
.
This separates your core business logic from framework-specific response methods, keeping your code cleaner by delegating response handling to the handlers.
Suvidha as data validation middleware
To use Suvidha solely as data validation middleware with TypeScript inference, implementonSchemaErr
method.
DRY Suvidha
If you have common middlewares across multiple routes, you can create aSuvidha
instance and reuse it.
Adopting Suvidha in Existing Projects
Suvidha’sCtxRequest
extends the standard Request
object by adding a context
property.
Existing handlers that accept Request
will also work with CtxRequest
. The context
can be accessed using CtxRequest
.