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
TypeScript interfaces and types for Express-based NestJS applications, providing Express-specific methods and configurations for HTTP handling, static files, view rendering, and body parsing.
Main application interface extending NestJS's INestApplication with Express-specific functionality.
/**
* Interface for Express-based NestJS applications
* Extends INestApplication with Express-specific methods and configurations
*/
interface NestExpressApplication<
TServer extends CoreHttpServer | CoreHttpsServer = CoreHttpServer
> extends INestApplication<TServer> {
/** Get the underlying Express HTTP adapter */
getHttpAdapter(): HttpServer<Express.Request, Express.Response, Express>;
/** Start the application server */
listen(port: number | string, callback?: () => void): Promise<TServer>;
listen(
port: number | string,
hostname: string,
callback?: () => void
): Promise<TServer>;
/** Configure Express application settings */
set(...args: any[]): this;
/** Configure view template engine */
engine(...args: any[]): this;
/** Enable Express features */
enable(...args: any[]): this;
/** Disable Express features */
disable(...args: any[]): this;
/** Serve static files from directory */
useStaticAssets(options: ServeStaticOptions): this;
useStaticAssets(path: string, options?: ServeStaticOptions): this;
/** Enable Cross-Origin Resource Sharing */
enableCors(options?: CorsOptions | CorsOptionsDelegate<any>): void;
/** Configure Express body parser */
useBodyParser<Options = NestExpressBodyParserOptions>(
parser: NestExpressBodyParserType,
options?: Omit<Options, 'verify'>
): this;
/** Set view template directories */
setBaseViewsDir(path: string | string[]): this;
/** Set view rendering engine */
setViewEngine(engine: string): this;
/** Set application-level template variables */
setLocal(key: string, value: any): this;
}Usage Examples:
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
// Create Express-based application
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// Configure Express features
app.set('trust proxy', true);
app.enable('case sensitive routing');
app.disable('x-powered-by');
// Set up static files and templates
app.useStaticAssets('public', { prefix: '/assets/' });
app.setBaseViewsDir('views');
app.setViewEngine('hbs');
// Configure CORS and body parsing
app.enableCors({ origin: 'https://example.com' });
app.useBodyParser('json', { limit: '10mb' });
await app.listen(3000);Configure static file serving with various options for caching, security, and URL handling.
/**
* Options for serving static files with Express
* Controls caching, security, and file handling behavior
*/
interface ServeStaticOptions {
/** How to treat dotfiles: 'allow', 'deny', or 'ignore' */
dotfiles?: string;
/** Enable or disable etag generation */
etag?: boolean;
/** File extension fallbacks for requests without extensions */
extensions?: string[];
/** Enable directory fallthrough on file not found */
fallthrough?: boolean;
/** Enable immutable cache-control directive */
immutable?: boolean;
/** Directory index file configuration */
index?: boolean | string | string[];
/** Enable Last-Modified header */
lastModified?: boolean;
/** Cache max-age in milliseconds or time string */
maxAge?: number | string;
/** Enable redirect for trailing slash on directories */
redirect?: boolean;
/** Function to set custom headers on responses */
setHeaders?: (res: any, path: string, stat: any) => any;
/** URL prefix for serving static files */
prefix?: string;
}Usage Examples:
// Basic static file serving
app.useStaticAssets('public');
// Static files with prefix
app.useStaticAssets('uploads', { prefix: '/files/' });
// Advanced static file configuration
app.useStaticAssets('assets', {
maxAge: '1y',
etag: true,
immutable: true,
extensions: ['html', 'htm'],
setHeaders: (res, path, stat) => {
if (path.endsWith('.js')) {
res.set('Content-Type', 'application/javascript');
}
}
});
// Multiple static directories
app.useStaticAssets('public');
app.useStaticAssets('uploads', { prefix: '/media/' });
app.useStaticAssets('assets', { prefix: '/static/' });Configure Express body parsing with support for different content types and raw body access.
/**
* Body parser types supported by Express
* Each type handles different content formats
*/
type NestExpressBodyParserType = 'json' | 'urlencoded' | 'text' | 'raw';
/**
* Configuration options for Express body parsers
* Supports various parsing limits and type filtering
*/
interface NestExpressBodyParserOptions {
/** Enable/disable gzip/deflate inflation of request body */
inflate?: boolean;
/** Request size limit (bytes, string with unit, or number) */
limit?: number | string;
/** Media type(s) to parse, string, array, or function */
type?: string | string[] | ((req: any) => any);
/** Additional parser-specific options */
[key: string]: any;
}Usage Examples:
// Configure JSON parser
app.useBodyParser('json', {
limit: '10mb',
type: 'application/json'
});
// Configure URL-encoded parser
app.useBodyParser('urlencoded', {
limit: '5mb',
extended: true,
parameterLimit: 1000
});
// Configure text parser
app.useBodyParser('text', {
limit: '1mb',
type: 'text/*'
});
// Configure raw buffer parser
app.useBodyParser('raw', {
limit: '50mb',
type: 'application/octet-stream'
});
// Configure with custom type detection
app.useBodyParser('json', {
type: (req) => req.headers['content-type'] === 'application/vnd.api+json'
});Type definitions for HTTP servers used with Express applications.
import type { Server as CoreHttpServer } from 'http';
import type { Server as CoreHttpsServer } from 'https';
import type { Express } from 'express';
/** Generic server type that can be HTTP or HTTPS */
type ExpressServer = CoreHttpServer | CoreHttpsServer;
/** Express application instance type */
type ExpressInstance = Express;Types for Cross-Origin Resource Sharing configuration (imported from @nestjs/common).
/** CORS configuration options */
interface CorsOptions {
/** Allowed origins */
origin?: boolean | string | RegExp | (string | RegExp)[] |
((origin: string, callback: (err: Error | null, allow?: boolean) => void) => void);
/** Allowed HTTP methods */
methods?: string | string[];
/** Allowed headers */
allowedHeaders?: string | string[];
/** Exposed headers */
exposedHeaders?: string | string[];
/** Allow credentials */
credentials?: boolean;
/** Max age for preflight cache */
maxAge?: number;
/** Enable preflight pass-through */
preflightContinue?: boolean;
/** Success status for OPTIONS requests */
optionsSuccessStatus?: number;
}
/** Dynamic CORS configuration function */
type CorsOptionsDelegate<T = any> = (
req: T,
callback: (err: Error | null, options?: CorsOptions) => void
) => void;Usage Examples:
// Simple CORS configuration
app.enableCors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
credentials: true
});
// Multiple origins
app.enableCors({
origin: [
'https://example.com',
'https://app.example.com',
/\.example\.com$/
]
});
// Dynamic CORS configuration
app.enableCors((req, callback) => {
const corsOptions: CorsOptions = {
origin: req.headers.origin === 'https://trusted.com',
credentials: true
};
callback(null, corsOptions);
});
// Development vs production CORS
const corsOptions: CorsOptions = {
origin: process.env.NODE_ENV === 'development'
? true
: ['https://app.example.com'],
credentials: true,
optionsSuccessStatus: 200
};
app.enableCors(corsOptions);Methods for managing application startup and HTTP server binding.
/**
* Start the NestJS application server
* Returns a Promise that resolves to the underlying HTTP server
*/
listen(port: number | string, callback?: () => void): Promise<TServer>;
listen(
port: number | string,
hostname: string,
callback?: () => void
): Promise<TServer>;Usage Examples:
// Start server on port 3000
await app.listen(3000);
// Start with callback
await app.listen(3000, () => {
console.log('Application is running on http://localhost:3000');
});
// Start on specific hostname
await app.listen(3000, '0.0.0.0', () => {
console.log('Server started on all interfaces');
});
// Store server reference
const server = await app.listen(3000);
console.log('Server type:', server.constructor.name); // 'Server'
// Graceful shutdown
process.on('SIGTERM', async () => {
await app.close();
process.exit(0);
});