skip to content

In NestJS, what changes when a route handler injects the response with @Res(), and when do you need @Res({ passthrough: true })?

level: middleimportance: should knowfreq 45%

answer

  1. standard versus library-specific mode
  2. return value no longer sent
  3. forgotten send means a hang
  4. cookies while Nest still responds

basics

~20 s

Injecting @Res() or @Next() puts the handler in library-specific mode: Nest stops sending its return value, so the handler must write the response or the request hangs. @Res({ passthrough: true }) exposes the native object while Nest still sends the return value.

solid answer

~40 s

By default Nest sends whatever the handler returns, which is also what interceptors see and transform. Once a handler declares `@Res()` (an alias of `@Response()`) or `@Next()`, Nest treats the response as yours: the return value, and any interceptor's mapping of it, is never written, so you must call `res.json()`, `res.send()` or similar yourself or the client waits forever. The code also becomes tied to the Express (or Fastify) API and needs a mocked response in unit tests. When you only need the native object for a side effect, such as setting a cookie or a header computed at runtime, use `@Res({ passthrough: true })`: you touch `res`, then return the value and Nest sends it as usual. For fixed statuses, headers and redirects, prefer `@HttpCode()`, `@Header()` and `@Redirect()`.

code

typescript · 16 lines
typescript
import { Controller, Get, Res } from '@nestjs/common';
import type { Response } from 'express';

@Controller('session')
export class SessionController {
  @Get('broken')
  broken(@Res() res: Response) {
    return { ok: true }; // never sent: the request hangs
  }

  @Get('fixed')
  fixed(@Res({ passthrough: true }) res: Response) {
    res.cookie('seen', '1');
    return { ok: true }; // sent by Nest, with the cookie
  }
}

go deeper

for a junior

Recall that returning a value is the normal way to respond, and that @Res() means you must send the response yourself.

for a middle

Explain how @Res() or @Next() flips the handler into library-specific mode, why that hangs a forgetful handler, and what passthrough keeps working.

for a senior

Diagnose an interceptor or envelope that silently skips one route, and steer @Res() uses toward @HttpCode, @Header, @Redirect or passthrough.

for a principal

Set a team rule for when raw response access is allowed, since it ties controllers to one HTTP adapter and complicates tests.

## Two ways to answer a request Nest offers two response modes for a route handler: - **Standard mode** (recommended): the handler returns a value, a `Promise` or an `Observable`. Nest serializes objects and arrays to JSON, sends primitives as they are, and sets 200, or 201 for `@Post()`. - **Library-specific mode**: the handler receives the platform's own response object, Express's `res` by default, through `@Res()` (an alias of `@Response()`), and answers with its native methods such as `res.status(201).json(body)`. Nest decides the mode per handler. If any parameter is decorated with `@Res()` or `@Next()` and passthrough is not enabled, the handler is in library-specific mode. ## What library-specific mode switches off 1. **The return value is not sent.** Nest still calls the handler and still runs interceptors around it, but it never writes the result. Anything an interceptor maps onto the result is discarded with it. 2. **You own the response.** If the handler returns without calling `res.json()`, `res.send()`, `res.end()` or a similar method, the request **hangs** until the client or a proxy times out. 3. **Portability and testing suffer.** The code depends on Express's response API, which differs from Fastify's, and unit tests need a mocked response object instead of asserting on a return value. Nest sets the `@HttpCode()` status and `@Header()` headers on the response before it calls the handler, but anything the handler later writes through `res` overrides them, so mixing the two styles is easy to misread in review. ## Passthrough: the native object as a side channel `@Res({ passthrough: true })` injects the same native object but keeps standard mode. The handler can do the one thing the decorators cannot express, then return normally: ```typescript @Get('profile') profile(@Res({ passthrough: true }) res: Response) { res.cookie('seen', '1', { httpOnly: true }); return { name: 'Ada' }; // still serialized and sent by Nest } ``` Typical uses are a cookie whose value is computed in the handler, a header that depends on the request, or a status set conditionally with `res.status()`. ## The declarative alternatives Most reasons to reach for `@Res()` already have a decorator: | Need | Declarative way | Library-specific way | |---|---|---| | Fixed status | `@HttpCode(204)` | `res.status(204).send()` | | Static header | `@Header('Cache-Control', 'no-store')` | `res.header(...)` | | Redirect | `@Redirect(url, status)` | `res.redirect(status, url)` | | Error status | throw an `HttpException` subclass | `res.status(404).json(...)` | `@Redirect()` takes an optional `url` and `statusCode`; the status defaults to **302**. When the handler returns an object of the shape `{ url, statusCode }` (the `HttpRedirectResponse` interface), the returned values override the decorator's arguments, which is how you redirect dynamically without touching `res`. ## When library-specific mode is still the right call - Streaming a large file or a proxied upstream body directly onto `res`. - Handing the request to a library that expects the raw Express `req` and `res` pair. - Calling `next()` deliberately through `@Next()` to defer to another handler. In each case, make sure every branch of the handler ends the response, including the error branches. ## Reviewing a handler that injects the response When a pull request adds `@Res()` to a controller, these checks catch most problems: 1. **Is the native object really needed?** A fixed status, a static header, a redirect or an error status each has a declarative form, and a computed cookie or header only needs passthrough. 2. **Does every path send exactly once?** Early returns, `catch` blocks and validation branches are where a forgotten `res.json()` turns into a hung request, and a second send fails with Node's "Cannot set headers after they are sent to the client" error. 3. **Do global interceptors matter here?** Response envelopes, serialization and caching interceptors that map the return value will not shape this route's output. 4. **Is the adapter pinned?** Calls such as `res.cookie()` and `res.redirect()` are Express API; the same code will not run on the Fastify adapter. 5. **How is it tested?** A unit test must now mock `status`, `json` and friends instead of asserting on a returned value. `@Next()` deserves the same scrutiny: injecting it also switches the handler to library-specific mode, and calling `next()` hands the request to the next matching handler registered on the adapter, which may be another route or Nest's 404 handler.

  • How do you redirect to a URL computed at runtime without injecting @Res() in NestJS?
    Keep `@Redirect()` on the handler, optionally with a default URL, and return an object with `url` and, if needed, `statusCode`. Nest uses the returned values over the decorator's arguments; with neither a returned nor a declared status, it sends 302.
  • Why does an interceptor that wraps every response in an envelope stop working on one NestJS route?
    That route almost certainly injects `@Res()` or `@Next()` without passthrough. The interceptor still runs and maps the handler's return value, but in library-specific mode Nest never writes that value; what reaches the client is whatever the handler wrote through `res`.

  • With @Res(), Nest still sends the returned value if the handler forgets to.
  • Passthrough mode stops Nest from serializing the return value.
  • @Res() is the normal way to set a fixed status code in Nest.
  • @Redirect() without a status code sends 301.
  • Injecting @Next() has no effect on how Nest sends the response.