Skip to content

Fundamentals

Modules, providers, guards, pipes, interceptors, filters — the vocabulary every NestRS app is built from.

A NestRS app is a tree of modules. Each module groups providers (injectable structs) and optionally imports other modules. The dependency-injection graph is built at compile time and verified at boot — a missing wire fails startup with a clear error, never with a deep Cannot resolve at first request.

This category walks blog through the Publish story — from the shape nestrs new writes (step ①: BlogService / BlogController in a feature’s adapter, a root importing it, no database) to a composed API with a posts/ feature, the stage the tutorial builds in the repo — and the primitives every binary leans on:

  • Modules — the composition unit. #[module] declares what a module owns and what it depends on.
  • Providers — the things modules own. Anything #[injectable] (services, controllers, …) is built once and shared as Arc<T>.
  • Lifecycle — the moments an app comes alive and winds down. #[hooks] tags async methods for the init and shutdown phases the framework drains in order. See Lifecycle.
  • Guards — decide who gets through. A guard writes its decision once, Guard::check, which runs on every unit and on an HTTP request through Guard::check_http; it returns Err(Denial) to short-circuit the chain, or attaches context the handler reads back via Ambient<T>.
  • Pipes — convert input at the request boundary. Stateless transforms (Parse<T>, ParseUuid, Trim, …) bound on any edge through Piped; an argument whose type declares rules is validated there with no pipe.
  • Interceptors — wrap handler execution, after the guards: time it, decorate the reply, or answer in its place.
  • Error handling — map errors to responses. ToProblem on the error type for the default, on every edge; #[use_exception_filters(...)] for a typed catch or one envelope for every error. See Error handling.
  • Middleware — NestRS doesn’t have a middleware primitive. See the page for the Guards/Interceptors split if you’re looking for one.

Step ① of the blog story. The domain lives in crates/features/, where every app can reach it; the app crate under apps/ only wires modules together, which is why no service.rs or controller.rs appears there.

crates/features/src/blog/service.rs
use nest_rs::core::injectable;
#[injectable]
pub struct BlogService;
impl BlogService {
pub fn tagline(&self) -> &'static str {
"A minimal blog API"
}
}

A service is an injectable struct. Anything decorated with #[injectable] is registered with the container and shared as Arc<T>.

crates/features/src/blog/http/controller.rs
use std::sync::Arc;
use nest_rs::http::{controller, routes};
use crate::blog::BlogService;
#[controller(path = "/")]
pub struct BlogController {
#[inject]
svc: Arc<BlogService>,
}
#[routes]
impl BlogController {
#[get("/")]
#[public]
async fn root(&self) -> &'static str {
self.svc.tagline()
}
}

A controller is also a provider. #[inject] fields are resolved by type from the container; #[routes] mounts the verb methods on the controller’s path. #[public] is the route’s posture: a route no guard covers either says #[public] or refuses the boot, which names it. This tagline is open on purpose, so it says so; Guards covers the other half.

crates/features/src/blog/module.rs
use nest_rs::core::module;
use super::service::BlogService;
#[module(providers = [BlogService])]
pub struct BlogModule;
crates/features/src/blog/http/module.rs
use nest_rs::core::module;
use super::controller::BlogController;
use crate::blog::BlogModule;
#[module(imports = [BlogModule], providers = [BlogController])]
pub struct BlogHttpModule;

The port owns the service, the adapter owns the handler and imports the port, and the app’s root imports the adapter:

apps/blog/src/module.rs
use nest_rs::core::module;
use features::blog::BlogHttpModule;
#[module(imports = [BlogHttpModule])]
pub struct BlogModule;
apps/blog/src/main.rs
use blog::BlogModule;
use nest_rs::core::App;
#[nest_rs::main]
async fn main() -> anyhow::Result<()> {
App::builder()
.module::<BlogModule>()
.build()
.await?
.run()
.await
}

nestrs new writes the same main with one more line, let _otel = OpenTelemetry::init()?;, the telemetry a project starts with.

Terminal window
$ curl http://localhost:3000/
A minimal blog API

Later pages give the domain a feature of its own, posts/ (PostsService, PostsController, PostsModule, …), and grow the app’s BlogModule into a composed root — see Modules. The tutorial is where you implement that composed root in the repo.

  1. Collected every provider in the import tree — BlogService, BlogController — into a link-time registry.
  2. Built the access graph from the app’s BlogModule. BlogController declares it injects BlogService; BlogHttpModule imports the port that owns it; reachable. ✓
  3. Constructed each provider once. BlogService became one Arc<BlogService>, injected into BlogController::svc.
  4. Mounted BlogController on the HTTP transport from the route table #[routes] generated.

Empty the port’s providers, the line that lists BlogService, then build:

Terminal window
Error: unmet dependency: `BlogController` (in module `BlogHttpModule`) depends on `BlogService`, but no module provides it and it is not global infrastructure (a seed or factory output). Import the module that opens it, add a provider for `BlogService` to a module reachable from the root, or seed it at `App::builder()`.

The error names the consumer (BlogController), the missing dependency (BlogService), and the ways to fix it. Boot fails inside build().await, before the HTTP transport starts — never at the first request.

  • Module — a struct decorated with #[module], listing providers it owns and imports it depends on. Modules walks blog from here to a composed root.
  • Provider — any injectable struct (#[injectable], #[controller], …). Built once, shared as Arc<T>. Providers follows the same posts/ split.
  • #[inject] field — declares “I need this type from the container.”
  • Access graph — boot-time check that proves every #[inject] resolves to a provider the module can reach.
  • Discoverable — every decorated provider registers itself; transports consume the registry filtered by reachability.

Each primitive below gets its own page — concept, signature, where to bind it, and a tested example. Handler types (controllers, resolvers, gateways, processors, MCP tools) are transport-specific and live in their own categories: HTTP, GraphQL, WebSockets, Queue, MCP.

  • Modules — the composition unit, imports, and the port + adapters layout.
  • Providers — injectables and the boot-time access graph.
  • Guards — pre-handler gates: write one, read an earlier guard’s principal, document what it refuses.
  • Guard scopes — a controller, a route or the app’s pool, composed outermost first, declared on the provider.
  • Pipes — parse, normalize and validate at the request boundary.
  • Interceptors — wrap a unit on every edge, install ambient state, shape the reply.
  • Error handling — typed catches, unconditional mapping, and the defaults underneath.
  • Module boot — the phases a boot runs over the import tree, what is global, and a module imported twice.
  • Provider scopes — singleton, request or transient, and how a handler reaches a scoped provider.
  • Providers behind a trait — bind Impl as dyn Trait, so another feature injects the port alone.
  • Instances — one resource opened twice, each instance a type of its own.
  • Lifecycle — #[hooks] on the init and shutdown phases the framework drains in order.
  • App state — the sequence App::run walks, and where the app stands on it.
  • Shutdown — every bounded step from the signal to the exit.
  • The request lifecycle — the stages every unit runs, and one pool per layer family, run exactly once.
  • Execution context — what every layer reads about the unit it runs around, on every edge.
  • Guard context — what a guard attaches, the route metadata and posture it reads, the body it may read.
  • Guards beyond HTTP — one guard on GraphQL fields, WebSocket messages and MCP operations.
  • Pipes beyond HTTP — the same pipes on every edge’s wire value.
  • Global pipes — one pipe over every body, set of variables and message.
  • Interceptors beyond HTTP — an interceptor around a GraphQL root field, the three places that run less, and the table linking every other edge.
  • Middleware — why there is no middleware primitive, and which of the layers you actually want.
  • Correlation — the W3C trace every unit of work runs under, readable anywhere.
  • Architecture and naming — the role tables, the five naming levels, and the reserved vocabulary.
  • Tutorial — build the composed posts/ root end to end.
  • HTTP — the first transport to mount on this vocabulary.
  • Extending NestRS — a package, a transport, a decorator or a driver of your own, on the same vocabulary.