Server Utilities
New project? See Getting Started for install order and Express / Fastify / Next.js recipes.
@brushy/di provides specific utilities for managing dependency injection on the server side, especially useful in Node.js applications and frameworks like Next.js, Express, NestJS, etc.
server
Theserver object provides methods for managing containers in the server context.
Import
Server Container Configuration
Get Server Container
Dependency Resolution
Automatic Request Scope (AsyncLocalStorage)
On Node.js, preferserver.brushyRequestScope() or runInRequestScope() - they bind the active request scope via AsyncLocalStorage, so resolve() / inject.resolve() pick up scoped instances without passing a scope manually.
isRequestScopeSupported() returns whether ALS is available (Node.js). On React Native / browsers, scoped resolution still works when you pass an explicit scope.
Request Scope Cleanup (manual)
If you cannot use ALS middleware, callserver.clearRequestScope() after each HTTP request.
Complete Example with Express
Example with Next.js App Router
Best Practices
-
Prefer
brushyRequestScope(): On Node.js, useserver.brushyRequestScope()orrunInRequestScope()instead of manualclearRequestScope()in every route. -
Use appropriate lifecycle: For shared services, use
singleton. For request-specific services, usescoped. - Initialize container only once: In serverless applications like Next.js, make sure to initialize the container only once to avoid overhead.
- Manage resource connections: For resources like database connections, consider using the container lifecycle to manage connections.
- Isolate test scopes: During testing, create isolated containers to avoid interference between tests.