Express.js HTTP platform adapter for NestJS applications with comprehensive file upload capabilities
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core Express.js integration for NestJS providing HTTP server functionality, middleware support, static file serving, view rendering, CORS support, and request/response lifecycle management.
Main HTTP adapter class that bridges NestJS's abstract HTTP adapter interface with Express-specific functionality.
/**
* Express HTTP adapter for NestJS applications extending AbstractHttpAdapter
* Provides Express-specific implementations for HTTP operations, middleware, and server management
*/
class ExpressAdapter extends AbstractHttpAdapter<http.Server | https.Server> {
/** Creates adapter with optional Express instance */
constructor(instance?: any);
/** Start the HTTP server on specified port */
listen(port: string | number, callback?: () => void): Server;
listen(port: string | number, hostname: string, callback?: () => void): Server;
/** Close the server and all open connections */
close(): Promise<void>;
/** Send response with optional status code */
reply(response: any, body: any, statusCode?: number): void;
/** Set response status code */
status(response: any, statusCode: number): any;
/** End response with optional message */
end(response: any, message?: string): any;
/** Render view template with data */
render(response: any, view: string, options: any): any;
/** Redirect response to URL with status code */
redirect(response: any, statusCode: number, url: string): any;
}Usage Examples:
import { ExpressAdapter } from '@nestjs/platform-express';
import { NestFactory } from '@nestjs/core';
// Using default Express instance
const adapter = new ExpressAdapter();
const app = await NestFactory.create(AppModule, adapter);
// Using custom Express instance
import * as express from 'express';
const expressApp = express();
const customAdapter = new ExpressAdapter(expressApp);
const app = await NestFactory.create(AppModule, customAdapter);
await app.listen(3000);Configure Express application settings and features.
/** Express app.set() wrapper for application settings */
set(...args: any[]): any;
/** Express app.enable() wrapper to enable features */
enable(...args: any[]): any;
/** Express app.disable() wrapper to disable features */
disable(...args: any[]): any;
/** Express app.engine() wrapper for template engines */
engine(...args: any[]): any;Usage Examples:
// Configure Express settings
app.getHttpAdapter().set('trust proxy', true);
app.getHttpAdapter().enable('case sensitive routing');
app.getHttpAdapter().disable('x-powered-by');
// Set up view engine
app.getHttpAdapter().engine('hbs', require('hbs').__express);Serve static files with Express middleware.
/**
* Serve static files from specified directory
* @param path - Directory path containing static files
* @param options - Static file serving options with optional prefix
*/
useStaticAssets(path: string, options: ServeStaticOptions): void;Usage Examples:
// Serve files from 'public' directory
app.useStaticAssets('public');
// Serve with URL prefix
app.useStaticAssets('assets', { prefix: '/static/' });
// Serve with custom options
app.useStaticAssets('uploads', {
maxAge: '1d',
etag: true,
setHeaders: (res, path, stat) => {
res.set('X-Custom-Header', 'value');
}
});Configure template rendering with various view engines.
/**
* Set base directory for view templates
* @param path - Single directory path or array of paths
*/
setBaseViewsDir(path: string | string[]): any;
/**
* Set view engine for template rendering
* @param engine - View engine name (e.g., 'hbs', 'ejs', 'pug')
*/
setViewEngine(engine: string): any;
/**
* Set app-level locals for view templates
* @param key - Local variable name
* @param value - Variable value
*/
setLocal(key: string, value: any): this;Usage Examples:
// Configure Handlebars
app.setViewEngine('hbs');
app.setBaseViewsDir('views');
app.setLocal('title', 'My NestJS App');
// Multiple view directories
app.setBaseViewsDir(['views', 'templates']);
// Set global template variables
app.setLocal('appVersion', '1.0.0');
app.setLocal('isDevelopment', process.env.NODE_ENV === 'development');Enable Cross-Origin Resource Sharing with Express CORS middleware.
/**
* Enable CORS with optional configuration
* @param options - CORS options or delegate function
*/
enableCors(options?: CorsOptions | CorsOptionsDelegate<any>): void;Usage Examples:
// Enable CORS with default settings
app.enableCors();
// Configure CORS options
app.enableCors({
origin: ['http://localhost:3000', 'https://example.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
optionsSuccessStatus: 200
});
// Dynamic CORS configuration
app.enableCors((req, callback) => {
const corsOptions = {
origin: req.header('Origin') === 'https://trusted-domain.com'
};
callback(null, corsOptions);
});Configure Express body parsing middleware with support for different content types.
/**
* Register Express body parser with raw body support
* @param type - Body parser type ('json', 'urlencoded', 'text', 'raw')
* @param rawBody - Enable raw body access
* @param options - Parser-specific options excluding 'verify' option
*/
useBodyParser<Options = NestExpressBodyParserOptions>(
type: NestExpressBodyParserType,
rawBody: boolean,
options?: Omit<Options, 'verify'>
): this;
/**
* Register default JSON and URL-encoded parsers
* @param prefix - Optional route prefix (unused in current implementation)
* @param rawBody - Enable raw body access for default parsers
*/
registerParserMiddleware(prefix?: string, rawBody?: boolean): void;Usage Examples:
// Configure JSON parser with size limit
app.useBodyParser('json', false, { limit: '10mb' });
// Configure URL-encoded parser
app.useBodyParser('urlencoded', false, {
limit: '5mb',
extended: true
});
// Configure text parser with raw body access
app.useBodyParser('text', true, {
type: 'text/plain',
limit: '1mb'
});
// Configure raw buffer parser
app.useBodyParser('raw', true, {
type: 'application/octet-stream',
limit: '50mb'
});Utility methods for handling HTTP requests and responses.
/** Get request hostname */
getRequestHostname(request: any): string;
/** Get request HTTP method */
getRequestMethod(request: any): string;
/** Get request original URL */
getRequestUrl(request: any): string;
/** Check if response headers have been sent */
isHeadersSent(response: any): boolean;
/** Get response header value by name */
getHeader(response: any, name: string): any;
/** Set response header */
setHeader(response: any, name: string, value: string): any;
/** Append value to response header */
appendHeader(response: any, name: string, value: string): any;Configure request and response processing hooks.
/**
* Set request lifecycle hook executed before route handlers
* @param onRequestHook - Function to execute on each request
*/
setOnRequestHook(
onRequestHook: (
req: express.Request,
res: express.Response,
done: () => void
) => Promise<void> | void
): void;
/**
* Set response lifecycle hook executed after response finishes
* @param onResponseHook - Function to execute when response completes
*/
setOnResponseHook(
onResponseHook: (
req: express.Request,
res: express.Response
) => Promise<void> | void
): void;Usage Examples:
// Request logging hook
app.getHttpAdapter().setOnRequestHook((req, res, done) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
done();
});
// Response timing hook
app.getHttpAdapter().setOnResponseHook((req, res) => {
const duration = Date.now() - req.startTime;
console.log(`Response completed in ${duration}ms`);
});
// Async hooks with error handling
app.getHttpAdapter().setOnRequestHook(async (req, res, done) => {
try {
await authenticateRequest(req);
done();
} catch (error) {
res.status(401).json({ error: 'Unauthorized' });
}
});Methods for server initialization and connection management.
/**
* Initialize HTTP or HTTPS server
* @param options - NestJS application options including HTTPS configuration
*/
initHttpServer(options: NestApplicationOptions): void;
/** Get the adapter type identifier */
getType(): string; // Returns 'express'Body parser configuration utilities.
/**
* Configure body parser options with optional raw body support
* @param rawBody - Enable raw body access in req.rawBody
* @param options - Parser options excluding 'verify' option
* @returns Enhanced options with verify function for raw body support
*/
function getBodyParserOptions<Options = NestExpressBodyParserOptions>(
rawBody: boolean,
options?: Omit<Options, 'verify'>
): Options;Usage Examples:
import { getBodyParserOptions } from '@nestjs/platform-express';
// Basic options without raw body
const jsonOptions = getBodyParserOptions(false, { limit: '10mb' });
// Options with raw body access
const rawOptions = getBodyParserOptions(true, {
limit: '5mb',
type: 'application/json'
});
// Use in custom Express setup
const express = require('express');
const app = express();
app.use(express.json(getBodyParserOptions(true, { limit: '1mb' })));interface ServeStaticOptions {
/** How to treat dotfiles ('allow', 'deny', 'ignore') */
dotfiles?: string;
/** Enable/disable etag generation */
etag?: boolean;
/** File extension fallbacks */
extensions?: string[];
/** Enable directory fallthrough */
fallthrough?: boolean;
/** Enable immutable cache directive */
immutable?: boolean;
/** Directory index file(s) */
index?: boolean | string | string[];
/** Enable Last-Modified header */
lastModified?: boolean;
/** Cache max-age in milliseconds or string */
maxAge?: number | string;
/** Enable redirect for trailing slash */
redirect?: boolean;
/** Custom header setting function */
setHeaders?: (res: any, path: string, stat: any) => any;
/** URL prefix for static files */
prefix?: string;
}
type NestExpressBodyParserType = 'json' | 'urlencoded' | 'text' | 'raw';
interface NestExpressBodyParserOptions {
/** Enable/disable body inflation */
inflate?: boolean;
/** Request size limit */
limit?: number | string;
/** Media type(s) to parse */
type?: string | string[] | ((req: any) => any);
/** Additional body-parser specific options */
[key: string]: any;
}