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 { Directive, ElementRef, HostListener, Input, OnDestroy, OnInit } from '@angular/core'; @Directive({ selector: '[appTrapFocus]',
Building a focus-trap directive in Angular
accessibility
focus-management
dom
Intermediate
9 steps
java
package com.example.payments.config; import com.stripe.StripeClient; import org.springframework.beans.factory.annotation.Value;
Swapping payment gateways by profile in Spring
dependency-injection
profiles
configuration
Intermediate
6 steps
typescript
type AsyncFn<A extends unknown[], R> = (...args: A) => Promise<R>; interface MemoizeOptions<A extends unknown[]> { keyFn?: (...args: A) => string;
Memoizing async functions with TTL in TypeScript
memoization
generics
promises
Advanced
8 steps
java
public class OrderSerializer { private final ObjectMapper mapper;
Configuring a reusable Jackson ObjectMapper
serialization
json
builder-pattern
Intermediate
8 steps
java
package com.example.maintenance; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
How a scheduled cleanup job runs in Spring
scheduling
cron
transactions
Intermediate
6 steps
typescript
interface PollOptions<T> { intervalMs?: number; timeoutMs?: number; signal?: AbortSignal;
A cancellable polling helper in TypeScript
polling
async-await
abortsignal
Intermediate
9 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.