or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-interface.mdexpress-adapter.mdfile-upload.mdindex.md

express-adapter.mddocs/

0

# Express HTTP Adapter

1

2

Core Express.js integration for NestJS providing HTTP server functionality, middleware support, static file serving, view rendering, CORS support, and request/response lifecycle management.

3

4

## Capabilities

5

6

### ExpressAdapter Class

7

8

Main HTTP adapter class that bridges NestJS's abstract HTTP adapter interface with Express-specific functionality.

9

10

```typescript { .api }

11

/**

12

* Express HTTP adapter for NestJS applications extending AbstractHttpAdapter

13

* Provides Express-specific implementations for HTTP operations, middleware, and server management

14

*/

15

class ExpressAdapter extends AbstractHttpAdapter<http.Server | https.Server> {

16

/** Creates adapter with optional Express instance */

17

constructor(instance?: any);

18

19

/** Start the HTTP server on specified port */

20

listen(port: string | number, callback?: () => void): Server;

21

listen(port: string | number, hostname: string, callback?: () => void): Server;

22

23

/** Close the server and all open connections */

24

close(): Promise<void>;

25

26

/** Send response with optional status code */

27

reply(response: any, body: any, statusCode?: number): void;

28

29

/** Set response status code */

30

status(response: any, statusCode: number): any;

31

32

/** End response with optional message */

33

end(response: any, message?: string): any;

34

35

/** Render view template with data */

36

render(response: any, view: string, options: any): any;

37

38

/** Redirect response to URL with status code */

39

redirect(response: any, statusCode: number, url: string): any;

40

}

41

```

42

43

**Usage Examples:**

44

45

```typescript

46

import { ExpressAdapter } from '@nestjs/platform-express';

47

import { NestFactory } from '@nestjs/core';

48

49

// Using default Express instance

50

const adapter = new ExpressAdapter();

51

const app = await NestFactory.create(AppModule, adapter);

52

53

// Using custom Express instance

54

import * as express from 'express';

55

const expressApp = express();

56

const customAdapter = new ExpressAdapter(expressApp);

57

const app = await NestFactory.create(AppModule, customAdapter);

58

59

await app.listen(3000);

60

```

61

62

### Server Configuration Methods

63

64

Configure Express application settings and features.

65

66

```typescript { .api }

67

/** Express app.set() wrapper for application settings */

68

set(...args: any[]): any;

69

70

/** Express app.enable() wrapper to enable features */

71

enable(...args: any[]): any;

72

73

/** Express app.disable() wrapper to disable features */

74

disable(...args: any[]): any;

75

76

/** Express app.engine() wrapper for template engines */

77

engine(...args: any[]): any;

78

```

79

80

**Usage Examples:**

81

82

```typescript

83

// Configure Express settings

84

app.getHttpAdapter().set('trust proxy', true);

85

app.getHttpAdapter().enable('case sensitive routing');

86

app.getHttpAdapter().disable('x-powered-by');

87

88

// Set up view engine

89

app.getHttpAdapter().engine('hbs', require('hbs').__express);

90

```

91

92

### Static File Serving

93

94

Serve static files with Express middleware.

95

96

```typescript { .api }

97

/**

98

* Serve static files from specified directory

99

* @param path - Directory path containing static files

100

* @param options - Static file serving options with optional prefix

101

*/

102

useStaticAssets(path: string, options: ServeStaticOptions): void;

103

```

104

105

**Usage Examples:**

106

107

```typescript

108

// Serve files from 'public' directory

109

app.useStaticAssets('public');

110

111

// Serve with URL prefix

112

app.useStaticAssets('assets', { prefix: '/static/' });

113

114

// Serve with custom options

115

app.useStaticAssets('uploads', {

116

maxAge: '1d',

117

etag: true,

118

setHeaders: (res, path, stat) => {

119

res.set('X-Custom-Header', 'value');

120

}

121

});

122

```

123

124

### View Engine Support

125

126

Configure template rendering with various view engines.

127

128

```typescript { .api }

129

/**

130

* Set base directory for view templates

131

* @param path - Single directory path or array of paths

132

*/

133

setBaseViewsDir(path: string | string[]): any;

134

135

/**

136

* Set view engine for template rendering

137

* @param engine - View engine name (e.g., 'hbs', 'ejs', 'pug')

138

*/

139

setViewEngine(engine: string): any;

140

141

/**

142

* Set app-level locals for view templates

143

* @param key - Local variable name

144

* @param value - Variable value

145

*/

146

setLocal(key: string, value: any): this;

147

```

148

149

**Usage Examples:**

150

151

```typescript

152

// Configure Handlebars

153

app.setViewEngine('hbs');

154

app.setBaseViewsDir('views');

155

app.setLocal('title', 'My NestJS App');

156

157

// Multiple view directories

158

app.setBaseViewsDir(['views', 'templates']);

159

160

// Set global template variables

161

app.setLocal('appVersion', '1.0.0');

162

app.setLocal('isDevelopment', process.env.NODE_ENV === 'development');

163

```

164

165

### CORS Support

166

167

Enable Cross-Origin Resource Sharing with Express CORS middleware.

168

169

```typescript { .api }

170

/**

171

* Enable CORS with optional configuration

172

* @param options - CORS options or delegate function

173

*/

174

enableCors(options?: CorsOptions | CorsOptionsDelegate<any>): void;

175

```

176

177

**Usage Examples:**

178

179

```typescript

180

// Enable CORS with default settings

181

app.enableCors();

182

183

// Configure CORS options

184

app.enableCors({

185

origin: ['http://localhost:3000', 'https://example.com'],

186

methods: ['GET', 'POST', 'PUT', 'DELETE'],

187

credentials: true,

188

optionsSuccessStatus: 200

189

});

190

191

// Dynamic CORS configuration

192

app.enableCors((req, callback) => {

193

const corsOptions = {

194

origin: req.header('Origin') === 'https://trusted-domain.com'

195

};

196

callback(null, corsOptions);

197

});

198

```

199

200

### Body Parser Configuration

201

202

Configure Express body parsing middleware with support for different content types.

203

204

```typescript { .api }

205

/**

206

* Register Express body parser with raw body support

207

* @param type - Body parser type ('json', 'urlencoded', 'text', 'raw')

208

* @param rawBody - Enable raw body access

209

* @param options - Parser-specific options excluding 'verify' option

210

*/

211

useBodyParser<Options = NestExpressBodyParserOptions>(

212

type: NestExpressBodyParserType,

213

rawBody: boolean,

214

options?: Omit<Options, 'verify'>

215

): this;

216

217

/**

218

* Register default JSON and URL-encoded parsers

219

* @param prefix - Optional route prefix (unused in current implementation)

220

* @param rawBody - Enable raw body access for default parsers

221

*/

222

registerParserMiddleware(prefix?: string, rawBody?: boolean): void;

223

```

224

225

**Usage Examples:**

226

227

```typescript

228

// Configure JSON parser with size limit

229

app.useBodyParser('json', false, { limit: '10mb' });

230

231

// Configure URL-encoded parser

232

app.useBodyParser('urlencoded', false, {

233

limit: '5mb',

234

extended: true

235

});

236

237

// Configure text parser with raw body access

238

app.useBodyParser('text', true, {

239

type: 'text/plain',

240

limit: '1mb'

241

});

242

243

// Configure raw buffer parser

244

app.useBodyParser('raw', true, {

245

type: 'application/octet-stream',

246

limit: '50mb'

247

});

248

```

249

250

### Request/Response Utilities

251

252

Utility methods for handling HTTP requests and responses.

253

254

```typescript { .api }

255

/** Get request hostname */

256

getRequestHostname(request: any): string;

257

258

/** Get request HTTP method */

259

getRequestMethod(request: any): string;

260

261

/** Get request original URL */

262

getRequestUrl(request: any): string;

263

264

/** Check if response headers have been sent */

265

isHeadersSent(response: any): boolean;

266

267

/** Get response header value by name */

268

getHeader(response: any, name: string): any;

269

270

/** Set response header */

271

setHeader(response: any, name: string, value: string): any;

272

273

/** Append value to response header */

274

appendHeader(response: any, name: string, value: string): any;

275

```

276

277

### Lifecycle Hooks

278

279

Configure request and response processing hooks.

280

281

```typescript { .api }

282

/**

283

* Set request lifecycle hook executed before route handlers

284

* @param onRequestHook - Function to execute on each request

285

*/

286

setOnRequestHook(

287

onRequestHook: (

288

req: express.Request,

289

res: express.Response,

290

done: () => void

291

) => Promise<void> | void

292

): void;

293

294

/**

295

* Set response lifecycle hook executed after response finishes

296

* @param onResponseHook - Function to execute when response completes

297

*/

298

setOnResponseHook(

299

onResponseHook: (

300

req: express.Request,

301

res: express.Response

302

) => Promise<void> | void

303

): void;

304

```

305

306

**Usage Examples:**

307

308

```typescript

309

// Request logging hook

310

app.getHttpAdapter().setOnRequestHook((req, res, done) => {

311

console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);

312

done();

313

});

314

315

// Response timing hook

316

app.getHttpAdapter().setOnResponseHook((req, res) => {

317

const duration = Date.now() - req.startTime;

318

console.log(`Response completed in ${duration}ms`);

319

});

320

321

// Async hooks with error handling

322

app.getHttpAdapter().setOnRequestHook(async (req, res, done) => {

323

try {

324

await authenticateRequest(req);

325

done();

326

} catch (error) {

327

res.status(401).json({ error: 'Unauthorized' });

328

}

329

});

330

```

331

332

### HTTP Server Management

333

334

Methods for server initialization and connection management.

335

336

```typescript { .api }

337

/**

338

* Initialize HTTP or HTTPS server

339

* @param options - NestJS application options including HTTPS configuration

340

*/

341

initHttpServer(options: NestApplicationOptions): void;

342

343

/** Get the adapter type identifier */

344

getType(): string; // Returns 'express'

345

```

346

347

### Utility Functions

348

349

Body parser configuration utilities.

350

351

```typescript { .api }

352

/**

353

* Configure body parser options with optional raw body support

354

* @param rawBody - Enable raw body access in req.rawBody

355

* @param options - Parser options excluding 'verify' option

356

* @returns Enhanced options with verify function for raw body support

357

*/

358

function getBodyParserOptions<Options = NestExpressBodyParserOptions>(

359

rawBody: boolean,

360

options?: Omit<Options, 'verify'>

361

): Options;

362

```

363

364

**Usage Examples:**

365

366

```typescript

367

import { getBodyParserOptions } from '@nestjs/platform-express';

368

369

// Basic options without raw body

370

const jsonOptions = getBodyParserOptions(false, { limit: '10mb' });

371

372

// Options with raw body access

373

const rawOptions = getBodyParserOptions(true, {

374

limit: '5mb',

375

type: 'application/json'

376

});

377

378

// Use in custom Express setup

379

const express = require('express');

380

const app = express();

381

app.use(express.json(getBodyParserOptions(true, { limit: '1mb' })));

382

```

383

384

## Types

385

386

```typescript { .api }

387

interface ServeStaticOptions {

388

/** How to treat dotfiles ('allow', 'deny', 'ignore') */

389

dotfiles?: string;

390

/** Enable/disable etag generation */

391

etag?: boolean;

392

/** File extension fallbacks */

393

extensions?: string[];

394

/** Enable directory fallthrough */

395

fallthrough?: boolean;

396

/** Enable immutable cache directive */

397

immutable?: boolean;

398

/** Directory index file(s) */

399

index?: boolean | string | string[];

400

/** Enable Last-Modified header */

401

lastModified?: boolean;

402

/** Cache max-age in milliseconds or string */

403

maxAge?: number | string;

404

/** Enable redirect for trailing slash */

405

redirect?: boolean;

406

/** Custom header setting function */

407

setHeaders?: (res: any, path: string, stat: any) => any;

408

/** URL prefix for static files */

409

prefix?: string;

410

}

411

412

type NestExpressBodyParserType = 'json' | 'urlencoded' | 'text' | 'raw';

413

414

interface NestExpressBodyParserOptions {

415

/** Enable/disable body inflation */

416

inflate?: boolean;

417

/** Request size limit */

418

limit?: number | string;

419

/** Media type(s) to parse */

420

type?: string | string[] | ((req: any) => any);

421

/** Additional body-parser specific options */

422

[key: string]: any;

423

}

424

```