typescript
42 lines · 8 steps
Request-scoped context service in NestJS
A request-scoped provider snapshots per-request metadata once at construction and exposes it safely to the rest of the app.
Explained by
highlit
1import { Injectable, Scope, Inject } from '@nestjs/common';
2import { REQUEST } from '@nestjs/core';
3import { Request } from 'express';
4
5export interface RequestContext {
6 requestId: string;
7 userId: string | null;
8 tenantId: string | null;
9 ip: string;
10}
11
12@Injectable({ scope: Scope.REQUEST })
13export class RequestContextService {
14 private readonly context: RequestContext;
15
16 constructor(@Inject(REQUEST) private readonly request: Request) {
17 const user = (request as Request & { user?: { id: string; tenantId?: string } }).user;
18
19 this.context = {
20 requestId:
21 (request.headers['x-request-id'] as string) ?? crypto.randomUUID(),
22 userId: user?.id ?? null,
23 tenantId: user?.tenantId ?? (request.headers['x-tenant-id'] as string) ?? null,
24 ip: request.ip ?? request.socket.remoteAddress ?? 'unknown',
25 };
26 }
27
28 get requestId(): string {
29 return this.context.requestId;
30 }
31
32 requireTenantId(): string {
33 if (!this.context.tenantId) {
34 throw new Error('No tenant bound to the current request');
35 }
36 return this.context.tenantId;
37 }
38
39 snapshot(): Readonly<RequestContext> {
40 return { ...this.context };
41 }
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Request-scoped providers give each HTTP request its own instance, so you can capture per-request state without threading it through every function.
- 2Computing derived context once in the constructor keeps reads cheap and guarantees a stable snapshot for the request's lifetime.
- 3Returning copies and requiring mandatory values guards callers from mutating shared state or silently proceeding with missing data.
Related explainers
typescript
import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, timer, throwError } from 'rxjs'; import { switchMap, takeWhile, filter, take, catchError } from 'rxjs/operators';
Polling a job until it finishes in Angular
rxjs
polling
observables
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Handling Stripe webhooks in Laravel
webhooks
signature-verification
dependency-injection
Intermediate
7 steps
typescript
type Flatten = Record<string, unknown>; function isPlainObject(value: unknown): value is Record<string, unknown> { return (
Flattening nested objects into dotted keys
recursion
reduce
type-guards
Intermediate
7 steps
typescript
import { Injectable, signal, computed, effect, inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; export type Theme = 'light' | 'dark';
A signal-based theme service in Angular
signals
reactivity
dependency-injection
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpClient, HttpEventType, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map, distinctUntilChanged, scan } from 'rxjs/operators';
Tracking upload progress in Angular
rxjs
http-events
state-reduction
Intermediate
8 steps
java
public final class CaseConverter { private static final Pattern CAMEL_BOUNDARY = Pattern.compile("([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])");
Converting camelCase to snake_case in Java
regex
string-manipulation
utility-class
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/request-scoped-context-service-in-nestjs-explained-typescript-b865/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.