Skip to main content
NestApplication is returned by NestFactory::create and acts as a builder for your HTTP server. Every method returns Self so you can chain calls fluently. Nothing binds to a network socket until you call listen, listen_graceful, or listen_with_shutdown. Call into_router() when you want the composed Axum Router without starting a listener—useful in tests or custom server setups.

Routing

set_global_prefix

Nests all application routes under a URL prefix. Health checks (/health, /ready), metrics (/metrics), and static file mounts are not affected.

enable_uri_versioning

Nests application routes under a URI version segment.

enable_api_versioning

Enables header- or media-type-based versioning using an ApiVersioningPolicy. Sets NestApiVersion on each request for guards and interceptors to read.

enable_header_versioning

Shorthand for header-based versioning. Reads the version from a request header (default: X-API-Version).

enable_media_type_versioning

Shorthand for Accept: ...;version=N style versioning.

Security

enable_cors

Installs a CORS layer using tower-http. Pass CorsOptions::permissive() for development or build a specific policy for production.
Using CorsOptions::permissive() in a production environment (detected via NESTRS_ENV, APP_ENV, or RUST_ENV) emits a tracing::warn log entry.

use_security_headers

Injects security-related response headers on every response.
SecurityHeaders::default() sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin, and X-XSS-Protection: 0. SecurityHeaders::helmet_like() also adds Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy, X-DNS-Prefetch-Control, X-Download-Options, and X-Permitted-Cross-Domain-Policies.

use_rate_limit

Installs a fixed-window rate limiter per client IP. Default: 100 requests per 60 seconds.
Distribute state across instances by adding .redis(url, key_prefix) to RateLimitOptions (requires the cache-redis feature).

use_csrf_protection

Enables double-submit CSRF middleware on POST, PUT, PATCH, and DELETE. Requires the csrf feature. Must be paired with use_cookies().

use_cookies

Enables tower_cookies::CookieManagerLayer for signed cookie handling. Requires the cookies feature.

use_session_memory

Enables in-memory server-side sessions via tower_sessions. Implies use_cookies. Requires the session feature.

Performance

use_request_timeout

Rejects requests that take longer than duration with 504 Gateway Timeout.

use_concurrency_limit

Caps the number of in-flight requests. Additional requests wait for capacity unless use_load_shed is also enabled, in which case they receive 503 Service Unavailable immediately.

use_load_shed

Enables Tower load shedding. Pair with use_concurrency_limit so overflow is rejected quickly rather than queued indefinitely.

use_body_limit

Rejects request bodies larger than max_bytes with 413 Payload Too Large.

use_compression

Enables gzip response compression via tower-http. Clients must advertise support with Accept-Encoding: gzip. Bodies smaller than 32 bytes are skipped.

use_request_decompression

Decodes Content-Encoding: gzip request bodies before they reach handlers. Unsupported encoding values yield 415 Unsupported Media Type.

Observability

use_request_tracing

Emits structured tracing log lines for each completed request with fields: method, path, status, duration_ms, and request_id.

use_request_id

Assigns a stable x-request-id UUID to each request (propagated from the client if already present) and echoes it on the response.

enable_metrics

Exposes a Prometheus scrape endpoint at path (default: "/metrics") with RED metrics: http_requests_total{method,status}, http_request_duration_seconds{method}, and http_requests_in_flight.

enable_health_check

Registers a minimal GET liveness probe at path that always returns {"status":"ok"} with status 200.
The probe is mounted at the server root—not under set_global_prefix or enable_uri_versioning—so orchestrators reach it without repeating API prefixes.

enable_readiness_check

Registers a GET readiness probe at path that runs all indicators on each request. Returns 200 when all indicators report Up, or 503 with a Terminus-style JSON body when any reports Down.

Launch

listen

Binds to port on 127.0.0.1 (or the address set by set_listen_ip) and starts serving. Runs lifecycle hooks in order: eager_init_singletons, on_module_init, on_application_bootstrap, scheduled tasks, queue processors.

listen_graceful

Like listen, but stops on Ctrl+C (all platforms) or SIGTERM (Unix). In-flight requests are drained before the process exits.

listen_with_shutdown

Like listen_graceful, but accepts an arbitrary Future as the shutdown signal. Useful for custom signal handlers or test harnesses.

into_router

Builds the axum::Router with all configured middleware and returns it without starting a server. Use this in integration tests or custom Axum server setups.

bind_all_interfaces

Sets the bind address to 0.0.0.0 so the server accepts connections on all IPv4 interfaces. Typical for containers and LAN access.

Additional builder methods

Apply any Tower layer to the full app after all built-in middleware. The first call is the innermost layer; the last call is the outermost (first to see the incoming request).
Register a global ExceptionFilter that runs for every response carrying an HttpException. The filter runs inside built-in layers such as CORS and rate limiting.
Strips internal detail from JSON 5xx bodies: sets message to a generic string and removes the errors field. Call enable_production_errors_from_env() to activate this automatically when NESTRS_ENV, APP_ENV, or RUST_ENV equals production or prod.
Normalizes request paths before routing. PathNormalization::TrimTrailingSlash rewrites /items//items. Only applied by listen and listen_graceful; into_router() ignores this setting.
Returns a ModuleRef for type-keyed resolution against the composed provider graph after NestFactory::create has run but before listen.