Headers — Reading & Setting

Pull From the Request, Push Into the Response

Headers — Reading & Setting

Read request headers with `@Headers`; set response headers with the `@Header` decorator or the response object.

4 min read Level 1/5 #nestjs#http#headers
What you'll learn
  • Read request headers with `@Headers`
  • Set response headers declaratively with `@Header`
  • Reach for the raw response object when you need flexibility

Headers carry the metadata that surrounds every HTTP request. Nest gives you one decorator for reading them and another for setting them — both much cleaner than poking at req.headers and res.setHeader directly.

Reading Request Headers

import { Controller, Get, Headers } from '@nestjs/common';

@Controller('me')
export class MeController {
  @Get()
  whoami(@Headers('authorization') auth: string | undefined) {
    return { auth };
  }
}

Header names are case-insensitive — Nest normalizes them. Omit the name to grab the whole headers object:

@Get()
whoami(@Headers() headers: Record<string, string>) {
  return headers;
}

Setting Response Headers Declaratively

Use the @Header decorator (singular) for static values you want on every response from a handler:

import { Controller, Get, Header } from '@nestjs/common';

@Controller('docs')
export class DocsController {
  @Get('terms')
  @Header('Cache-Control', 'public, max-age=31536000')
  @Header('X-Content-Type-Options', 'nosniff')
  terms() {
    return { version: 1, text: 'Welcome…' };
  }
}

Stack as many as you like; they all get applied before the body is sent.

Dynamic Headers

When the value depends on runtime data, fall back to the response object in passthrough mode — Nest still handles serialization:

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

@Controller('reports')
export class ReportsController {
  @Get(':id')
  async one(@Res({ passthrough: true }) res: Response) {
    const etag = await this.makeEtag();
    res.setHeader('ETag', etag);
    return { id: 1 };
  }
}

passthrough: true is the magic word. Without it, Nest assumes you’re taking over the response and stops auto-sending the return value.

Common Headers to Set

  • Cache-Control — caching policy.
  • Content-Dispositionattachment; filename="x.pdf" for downloads.
  • Set-Cookie — sessions; usually you use @nestjs/jwt or cookie-parser and the res.cookie(...) method instead.
  • X-RateLimit-* — rate limit headers (often added by middleware).

If a header applies to every route, write a small middleware or interceptor instead of repeating yourself on each handler.

HTTP Status Codes →