Skip to main content

InversifyExpressHttpAdapter (Express 4)

The Express 4 HTTP adapter implementation. This adapter allows you to use InversifyJS framework with Express v4.x applications.

Base class documentation

This adapter extends InversifyHttpAdapter. See the base class documentation for information about common methods like applyGlobalMiddleware, useGlobalFilters, applyGlobalGuards, useGlobalInterceptors, and useGlobalPipe.

Installation

npm install @inversifyjs/http-express-v4 express@^4.0.0 inversify reflect-metadata

Constructor

constructor(
container: Container,
httpAdapterOptions?: ExpressHttpAdapterOptions,
customApp?: Application,
)

Creates an Express 4 adapter instance.

Parameters

  • container: The Inversify container that holds controllers, guards, pipes, middleware, interceptors, and filters.
  • httpAdapterOptions (optional): Configuration options for the adapter. See Options below.
  • customApp (optional): A custom Express 4 application instance. If not provided, a default Express application is created.

Default Options

The adapter uses these defaults if not overridden:

{
logger: true,
useCookies: false,
useJson: true,
useText: false,
useUrlEncoded: false,
}

Methods

build

async build(): Promise<Application>

Builds and returns the Express 4 application with all configured routes, middleware, and handlers.

Returns: The Express 4 Application instance ready to be used with app.listen() or passed to http.createServer().

Options

ExpressHttpAdapterOptions

interface ExpressHttpAdapterOptions extends HttpAdapterOptions {
useCookies?: boolean;
useJson?: boolean;
useText?: boolean;
useUrlEncoded?: boolean;
}

Properties

  • logger (inherited): Set to true to log route mappings on build, or false to disable logging, or provide a custom logger implementing the Logger interface from @inversifyjs/logger.
  • useCookies: Enable cookie parsing middleware. Default: false
  • useJson: Enable JSON body parsing middleware. Default: true
  • useText: Enable text body parsing middleware. Default: false
  • useUrlEncoded: Enable URL-encoded body parsing middleware. Default: false

Usage Example

const container: Container = new Container();
// ... bind your controllers, services, etc.

// Create the adapter with options
const adapter: InversifyExpressHttpAdapter = new InversifyExpressHttpAdapter(
container,
{
logger: true,
useCookies: true,
useJson: true,
useUrlEncoded: true,
},
);

// Build the Express 4 application
const app: express.Application = await adapter.build();

// Start the server
app.listen(3000, () => {
console.log('Server listening on port 3000');
});

Type Parameters

The adapter is strongly typed with Express 4 types:

InversifyExpressHttpAdapter extends InversifyHttpAdapter<
Request, // Express 4 Request
Response, // Express 4 Response
NextFunction, // Express 4 NextFunction
void, // Handler return type
ExpressHttpAdapterOptions
>

See Also