Nestjs Request Context

screenshot of Nestjs Request Context
express

NestJS Request Context using AsyncLocalStorage

Overview

The nestjs-request-context is a powerful module designed for NestJS applications, enabling developers to store and access data within the request-scope effortlessly. This feature enhances the application's architecture by allowing any type of data to be accessible from various layers, including singleton service layers and repository layers. It operates efficiently under the Node.js environment, thanks to its reliance on AsyncLocalStorage, requiring Node.js version 14.15.2 or higher.

By simplifying the management of request-specific data, this module significantly improves the workflow for developers, making it easier to implement features that depend on request context without running into complications. Whether integrating with traditional HTTP requests or handling GraphQL subscriptions, nestjs-request-context provides a flexible approach to maintaining clean and organized code.

Features

  • Easy Integration: Seamlessly integrates into your NestJS application by importing the RequestContextModule into your AppModule for simplified configuration.

  • Middleware Support: Automatically registers middleware for each request, initializing a context that can be accessed across controllers, services, and repositories.

  • Request Context Management: Allows you to extend the request context by including custom data, ensuring that you have all the necessary information accessible throughout your application.

  • Functional Middleware Option: For those who prefer functional programming, you can opt to use the requestContextMiddleware function, providing flexibility in how the context is set up.

  • Support for Websocket Connections: Includes the ability to handle GraphQL subscriptions by allowing the request context to be initialized on a per-connection basis, ensuring context is maintained in real-time communication.

  • Global Module Option: Once loaded in the root module with the isGlobal flag set to true, there's no need to import the RequestContextModule into other modules, streamlining your application's architecture.

  • Node.js Compatibility: Built to work with Node.js version 14.15.2 or higher, leveraging modern JavaScript features for better performance and reliability.

express
Express

Express.js is a simple Node.js framework for single, multi-page, and hybrid web applications.

typescript
Typescript

TypeScript is a superset of JavaScript, providing optional static typing, classes, interfaces, and other features that help developers write more maintainable and scalable code. TypeScript's static typing system can catch errors at compile-time, making it easier to build and maintain large applications.