110 Nest building blocks: the official packages, every decorator you apply, and the pipes, guards, interceptors and filters that make up the request pipeline.
Topics
110
Sections
12
Core packages
@nestjs/core
The framework runtime: the DI container, module resolution, lifecycle and NestFactory.
The framework runtime holds the injection container and the request pipeline.
It is what turns decorated classes into a running application.
Everything else is layered on it, so its version anchors the rest.
@nestjs/common
Everything you import daily — decorators, pipes, guards, interceptors, exceptions and HttpModule helpers.
Decorators, pipes, guards and exceptions that application code uses daily.
Nearly every file imports from here rather than from core.
Its version must match core or decorator metadata disagrees.
@nestjs/platform-express
The default HTTP adapter. Express middleware and its ecosystem work unchanged underneath.
Express serves HTTP beneath the framework abstraction.
It is the default, so most middleware examples assume it.
Reaching for the raw request couples code to this platform.
@nestjs/platform-fastify
The Fastify adapter, for meaningfully higher throughput at the cost of Express-specific middleware.
Fastify replaces Express as the HTTP layer.
It is faster and stricter, which is the reason to switch.
Express-specific middleware does not carry over.
@nestjs/config
Typed configuration from env and files, with schema validation and namespaced registerAs factories.
Environment configuration is loaded, validated and injected.
Validating at boot turns a missing variable into a startup failure.
Reading process.env directly scatters the contract across the codebase.
@nestjs/swagger
Generates OpenAPI from decorators and DTOs, and serves Swagger UI.
OpenAPI documents are generated from decorators and DTOs.
Generating from code is what stops the document drifting from the routes.
Erased types need explicit decorators to appear at all.
@nestjs/cli
Scaffolding, build and the schematics behind nest generate.
Projects, modules and providers are scaffolded and built.
Generation enforces the conventions the framework expects.
Generated files still need wiring into the right module.
@nestjs/mapped-types
PartialType, PickType, OmitType and IntersectionType for deriving DTOs without copying them.
New DTOs derive from existing ones by picking or omitting fields.
Deriving keeps validation rules in one place.
A derived type inherits decorators, including ones that no longer apply.
@nestjs/terminus
Health check endpoints with indicators for databases, disk, memory and HTTP dependencies.
Health checks are exposed as a route with pluggable indicators.
A health endpoint is what an orchestrator uses to decide readiness.
A check that touches a dependency makes that dependency part of liveness.
@nestjs/event-emitter
In-process domain events with @OnEvent, for decoupling side effects from the request path.
In-process events decouple a producer from its consumers.
Decoupling keeps unrelated work out of the request path.
Events are lost on restart, unlike a queue.
@nestjs/schedule
@Cron, @Interval and @Timeout declarative scheduling with a lifecycle-aware registry.
Cron jobs, intervals and timeouts are declared with decorators.
Declaring them keeps scheduling visible beside the code it runs.
Every instance runs the job unless a lock prevents it.
@nestjs/bullmq
Redis-backed queues wired into DI, with @Processor and @OnWorkerEvent decorators.
Redis-backed queues run background jobs with retries.
A queue survives restarts, which an in-process event does not.
Redis becomes a hard dependency of the application.
@nestjs/cache-manager
Response and method caching with pluggable stores and the @CacheKey/@CacheTTL decorators.
Responses and values are cached behind a common interface.
One interface is what allows memory and Redis to swap.
A cached response can outlive the permission that allowed it.
@nestjs/throttler
Rate limiting as a guard, configurable globally or per route with @Throttle.
Request rate limits are applied per route or globally.
Limiting is what blunts brute force and abuse.
An in-memory counter is per instance, not per cluster.
Module system
@Module()
Declares imports, controllers, providers and exports — the unit the DI container resolves.
Controllers, providers, imports and exports are declared together.
A provider is injectable only where its module is imported or exported.
The module graph is the real architecture, not the folder layout.
@Global()
Makes a module's exported providers available everywhere without re-importing. Use sparingly.
A module's exports become available everywhere without importing.
It removes repetitive imports for genuinely cross-cutting modules.
It also hides dependencies, which is why it is used sparingly.
Dynamic modules
forRoot/forFeature static factories that return a module configured at import time.
A module is configured by the code importing it.
Configuration at import is what makes a module reusable.
Registering the same dynamic module twice can duplicate providers.
ConfigurableModuleBuilder
Generates the forRoot/forRootAsync boilerplate for a configurable module.
Boilerplate for sync and async module options is generated.
It produces the register and registerAsync pair consistently.
The generated names are conventional and must be followed.
forwardRef()
Resolves a genuine circular dependency between two modules or providers. A sign to reconsider the boundary.
A circular dependency between modules or providers is resolved.
It defers resolution until both sides exist.
A circular dependency is usually a design problem this merely defers.
ModuleRef
Resolves providers imperatively at runtime, including scoped ones outside a request.
Providers are resolved from the container at runtime.
It is the escape hatch when a dependency is only known then.
Resolving a scoped provider returns a new instance each call.
Lazy modules
LazyModuleLoader defers instantiation until first use, which matters for serverless cold starts.
A module loads on first use rather than at boot.
It shortens cold start where a feature is rarely reached.
The first request to that feature pays the load cost.
Controllers & routing
@Controller()
Binds a class to a route prefix and marks it as the HTTP entry point for its handlers.
A class handles requests under a route prefix.
The prefix is what groups related routes without repeating the path.
Business logic here cannot be reused by a queue consumer.
@Get / @Post / @Put / @Patch / @Delete
Map a method to an HTTP verb and a path, including parameters and wildcards.
Methods bind to HTTP verbs and sub-paths.
The verb is part of the contract, not decoration.
Route order matters, so a wildcard declared early shadows later routes.
@All / @Head / @Options
The remaining verb decorators, for catch-alls and preflight handling.
Less common verbs and catch-all handlers are declared.
OPTIONS matters for CORS preflight handling.
@All catches everything, including verbs you meant to reject.
@Param()
Extracts a route parameter, optionally through a pipe such as ParseIntPipe.
Route parameters are injected into the handler.
Injecting by name keeps the handler independent of the request object.
Every value arrives as a string until a pipe converts it.
@Query()
Extracts the parsed query string, whole or by key.
Query string values are injected.
A repeated key yields an array, which the DTO must allow for.
Query input is untrusted and needs the same validation as a body.
@Body()
Extracts the parsed request body — the usual place a validation pipe runs.
The parsed request body, or one property of it, is injected.
Binding to a DTO class is what makes validation possible.
Body parsing must be enabled and size-limited.
@Headers()
Extracts request headers, whole or by name.
Request headers are injected by name or as a whole.
Header names are case-insensitive, which the lookup handles.
Any header a client sends is untrusted input.
@Req() / @Res()
The underlying platform request and response. Taking @Res() opts out of Nest's response handling.
The underlying platform request and response are injected.
It is the escape hatch for what the framework does not expose.
Using @Res() disables the framework's own response handling.
@Session()
The session object, once session middleware is installed.
The session object is injected into the handler.
It requires session middleware to be configured first.
Session state is server-side and must be stored somewhere real.
@Ip() / @HostParam()
Client IP and subdomain parameters for host-based routing.
The client address and host sub-domain parameters are injected.
Host parameters are how multi-tenant subdomain routing works.
Behind a proxy the address is the proxy's unless trust is configured.
@HttpCode()
Overrides the success status code, which otherwise defaults to 200 or 201 on POST.
The success status code for a handler is set.
POST defaults to 201, which is often not what an action returns.
It sets the success code only, not the error codes.
@Header()
Sets a static response header on a handler.
A response header is added declaratively.
Declaring it keeps the header beside the route that needs it.
It applies to the success path, not to thrown exceptions.
@Redirect()
Declares a redirect, with the target overridable from the return value.
The handler responds with a redirect.
The target and status can be overridden by the returned value.
A redirect to a user-supplied URL is an open redirect.
@Render()
Renders a server-side template with the returned object as its model.
A server-side template renders with the returned data.
It requires a view engine to be configured on the application.
It is incompatible with returning JSON from the same handler.
@Sse()
Turns a handler returning an Observable into a Server-Sent Events stream.
The handler streams server-sent events from an observable.
It is the simplest push mechanism, needing no extra protocol.
Proxies may buffer the stream unless configured not to.
RouterModule
Declares route hierarchies across modules so prefixes live in one place.
Module route prefixes are declared in one hierarchy.
Centralising them is what keeps a large route tree comprehensible.
It duplicates path knowledge that also lives on the controllers.
Versioning
URI, header, media-type or custom API versioning, set globally and overridden with @Version().
Multiple API versions are served by URI, header or media type.
Versioning is what lets a breaking change ship without breaking clients.
Every version supported is a version that must be maintained.
Providers & DI
@Injectable()
Marks a class as a provider the container may construct and inject.
A class becomes a provider the container can construct.
The decorator is what emits the metadata injection relies on.
A class without it cannot receive constructor dependencies.
@Inject()
Injects by token rather than by type — for interfaces, constants and factory results.
A dependency is injected by token rather than by type.
Tokens are needed for interfaces and values, which have no runtime type.
A mistyped token fails at startup, not at the call site.
@Optional()
Allows a dependency to be missing instead of failing resolution.
A missing dependency resolves to undefined instead of failing.
It allows a provider to work with or without an optional collaborator.
It turns a wiring mistake into a silent undefined.
useClass / useValue / useFactory / useExisting
The four provider shapes: swap an implementation, supply a constant, compute one, or alias another token.
A token is bound to a class, a value, a factory or an alias.
useFactory is what allows a provider built from configuration.
useValue objects are shared, so mutating one affects every consumer.
Injection scopes
DEFAULT singletons, REQUEST per request and TRANSIENT per consumer. Request scope bubbles up and costs performance.
A provider is a singleton, per request, or transient.
Singleton is the default, which is why per-request state leaks.
A request-scoped provider makes everything depending on it request-scoped.
@INQUIRER
Injects the consuming class into a transient provider — the trick behind contextual loggers.
A provider learns which class asked for it.
It is how a logger labels itself with its consumer automatically.
It requires transient scope, so the provider is no longer shared.
Custom decorators
createParamDecorator builds reusable extractors such as @CurrentUser().
Parameter and metadata decorators remove repeated plumbing.
A parameter decorator keeps the handler signature honest.
Metadata decorators do nothing until a guard reads them.