@api-envelope/nestjs
v0.1.1
Published
nestjs dynamic module and injectable service for sending standardized API Envelope responses.
Downloads
267
Maintainers
Readme
@api-envelope/nestjs
nestjs dynamic module and injectable service for sending standardized API Envelope responses.
Unlike the other adapters, which each expose a single factory function,
this one follows Nest's dependency-injection conventions: register
ApiEnvelopeModule.forRoot() once, then inject ApiEnvelopeService
wherever you need it.
Table of contents
- Why use this
- Install
- Quick start
- Configuration — custom codes
- Type-safe custom codes
- Things to know
- API reference
- FAQ
- License
Why use this
Nest apps are already built around injecting shared, configured services
instead of importing bare functions everywhere. ApiEnvelopeService fits
that pattern directly — register it once in your root module, inject it
into any controller or provider, and every response in your app shares
the same envelope shape and code registry, without a factory call
scattered across files.
Install
npm install @api-envelope/nestjsRequires @nestjs/common and express (Nest's default HTTP adapter) in
your project. @api-envelope/core is installed automatically.
Quick start
// app.module.ts
import { Module } from "@nestjs/common";
import { ApiEnvelopeModule } from "@api-envelope/nestjs";
@Module({
imports: [ApiEnvelopeModule.forRoot()],
})
export class AppModule {}// users.controller.ts
import { Controller, Get, Res } from "@nestjs/common";
import type { Response } from "express";
import { ApiEnvelopeService } from "@api-envelope/nestjs";
@Controller("users")
export class UsersController {
constructor(private readonly envelope: ApiEnvelopeService) {}
@Get(":id")
getUser(@Res({ passthrough: true }) res: Response) {
const user = { id: 1, name: "Ada" };
return this.envelope.ok(res, { code: "OK", data: user });
}
@Get(":id/missing")
getMissingUser(@Res({ passthrough: true }) res: Response) {
return this.envelope.fail(res, { code: "NOT_FOUND", message: "User does not exist" });
}
}envelope.ok(res, ...) sets res.status to 200 and returns
{ success: true, code: "OK", status: 200, message: "...", data: {...} }
(Nest serializes the returned object as JSON since passthrough: true
was used). envelope.fail(res, ...) sets res.status to 404 and returns
{ success: false, code: "NOT_FOUND", status: 404, message: "User does not exist" }.
ApiEnvelopeModule.forRoot() is registered as a global module — call
it once, in your root module, and every feature module can inject
ApiEnvelopeService without importing ApiEnvelopeModule again.
Configuration — custom codes
// app.module.ts
@Module({
imports: [
ApiEnvelopeModule.forRoot({
codes: [
{ code: "USER_NOT_FOUND", status: 404 },
{ code: "EMAIL_EXISTS", status: 409 },
],
}),
],
})
export class AppModule {}// users.controller.ts
@Post()
createUser(@Res({ passthrough: true }) res: Response, @Body() body: CreateUserDto) {
if (await this.usersService.emailTaken(body.email)) {
return this.envelope.fail(res, { code: "EMAIL_EXISTS" });
}
const user = await this.usersService.create(body);
return this.envelope.ok(res, { code: "CREATED", data: user });
}Built-in codes (OK, SUCCESS, CREATED, NOT_FOUND, ...) are always
available; see @api-envelope/core
for the full default list.
Type-safe custom codes
import type { DefaultCode } from "@api-envelope/nestjs";
type AppCode = DefaultCode | "USER_NOT_FOUND" | "EMAIL_EXISTS";
return this.envelope.fail<AppCode>(res, { code: "EMAIL_EXISTS" }); // autocompleted & checkedThings to know
- Call
forRoot()exactly once, from your root module — it registersApiEnvelopeServiceglobally, so importingApiEnvelopeModuleagain in a feature module isn't necessary (and would create a second, separate code registry if you did). - Route handlers need
@Res({ passthrough: true }). Withoutpassthrough: true, Nest expects you to end the response yourself (res.send()), whichenvelope.ok/faildon't do. ApiEnvelopeServiceassumes an Express-basedResponse. If your Nest app uses the Fastify platform adapter instead, use@api-envelope/fastifydirectly on the underlying Fastify instance.- Custom codes can override defaults, the same as every other adapter.
API reference
ApiEnvelopeModule.forRoot(options?)
Returns a global DynamicModule that provides and exports
ApiEnvelopeService. options.codes is an optional array of
{ code, status } pairs registered on top of the built-in defaults.
envelope.ok(res, { code, data, message? })
Sets res.status to the matching HTTP status and returns the success
envelope for Nest to serialize.
envelope.fail(res, { code, message? })
Sets res.status to the matching HTTP status and returns the failure
envelope for Nest to serialize.
Both throw if code hasn't been registered — check for typos in custom
codes, or make sure options.codes was passed to ApiEnvelopeModule.forRoot().
Route handlers that use envelope.ok/envelope.fail need
@Res({ passthrough: true }) so Nest still serializes the returned value
instead of expecting you to call res.send() yourself.
FAQ
Why does Nest need @Res({ passthrough: true }) but Express doesn't?
Plain @api-envelope/express decorates res directly and ends the
response itself. Nest's ApiEnvelopeService.ok()/fail() only set the
status and return the body — passthrough: true tells Nest not to
short-circuit its own response pipeline, so it still serializes what you
return.
Can I inject ApiEnvelopeService into a guard or interceptor, not just a controller?
Yes — it's a normal @Injectable() provider, so it can be injected
anywhere Nest's DI container reaches.
Does forRoot() need to be called in every feature module?
No — call it once in your root module. global: true makes
ApiEnvelopeService available everywhere without re-importing.
Does this support Fastify-based Nest apps?
Not directly — ApiEnvelopeService types its res parameter as Express's
Response. For a Fastify-based Nest app, register
@api-envelope/fastify's plugin on the underlying Fastify instance
instead.
License
MIT © 2026 ltimsina
Copyright (c) [2026] [ltimsina]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
See also
@api-envelope/core— shared types and the code registry these helpers build on.
