npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@api-envelope/nestjs

v0.1.1

Published

nestjs dynamic module and injectable service for sending standardized API Envelope responses.

Downloads

267

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

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/nestjs

Requires @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 & checked

Things to know

  • Call forRoot() exactly once, from your root module — it registers ApiEnvelopeService globally, so importing ApiEnvelopeModule again in a feature module isn't necessary (and would create a second, separate code registry if you did).
  • Route handlers need @Res({ passthrough: true }). Without passthrough: true, Nest expects you to end the response yourself (res.send()), which envelope.ok/fail don't do.
  • ApiEnvelopeService assumes an Express-based Response. If your Nest app uses the Fastify platform adapter instead, use @api-envelope/fastify directly 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