Setting Custom Context for Requests for Nodejs
Set per-request context to surface important metadata when things go wrong.
Overview
The Hud SDK supports attaching custom context metadata to the forensics data on a current request or event being processed, whether it’s an HTTP request, a message from SQS, or any other handler. This context will be recorded and visible if the endpoint of queue fails or behaves unexpectedly, enabling richer debugging and investigation.
Use setContext() to inject metadata that is relevant to the current execution, such as clientId, messageId, userTier, or featureFlagStatus. The context is scoped to the current execution only, and is automatically cleared afterward.
When to Use
Use setContext if:
- You want extra identifiers in logs or error dashboards for specific requests or messages.
- You need metadata to trace failures or abnormal behaviors across systems (e.g. SQS).
- You want to correlate issues with tenants, plans, user types, or feature rollout states.
Important Notes
setContextmust be called during the active handling of a request or message.- It is per-invocation only. Calling it outside a request/message handler (e.g. in startup code) will have no effect.
- The context is automatically cleared after the handler completes.
- Keys are of type string
- Values are of the types: string | number | boolean | string[] | number[]
Example #1: Simple HTTP Handler
import { setContext } from 'hud-sdk/api';
export async function handleRequestOrMessage(request: any) {
// Set context for the current execution
setContext({
clientId: request.clientId,
requestId: request.id,
});
// Your actual logic here
console.log('Processing request:', request);
}Example #2: NestJS HTTP Interceptor
import { setContext } from 'hud-sdk/api';
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// Example dynamic context
setContext({
clientId: 'test',
other: 2,
});
const now = Date.now();
return next.handle().pipe(
tap(() => console.log(`Request took ${Date.now() - now}ms`))
);
}
}Updated 5 days ago
