Skip to main content

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

The server 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, prefer server.brushyRequestScope() or runInRequestScope() - they bind the active request scope via AsyncLocalStorage, so resolve() / inject.resolve() pick up scoped instances without passing a scope manually.
For scripts, tests, or non-HTTP flows:
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, call server.clearRequestScope() after each HTTP request.

Complete Example with Express

Example with Next.js App Router

Best Practices

  1. Prefer brushyRequestScope(): On Node.js, use server.brushyRequestScope() or runInRequestScope() instead of manual clearRequestScope() in every route.
  2. Use appropriate lifecycle: For shared services, use singleton. For request-specific services, use scoped.
  3. Initialize container only once: In serverless applications like Next.js, make sure to initialize the container only once to avoid overhead.
  4. Manage resource connections: For resources like database connections, consider using the container lifecycle to manage connections.
  5. Isolate test scopes: During testing, create isolated containers to avoid interference between tests.