or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

application-interface.mddocs/

0

# Application Interface

1

2

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.

3

4

## Capabilities

5

6

### NestExpressApplication Interface

7

8

Main application interface extending NestJS's INestApplication with Express-specific functionality.

9

10

```typescript { .api }

11

/**

12

* Interface for Express-based NestJS applications

13

* Extends INestApplication with Express-specific methods and configurations

14

*/

15

interface NestExpressApplication<

16

TServer extends CoreHttpServer | CoreHttpsServer = CoreHttpServer

17

> extends INestApplication<TServer> {

18

19

/** Get the underlying Express HTTP adapter */

20

getHttpAdapter(): HttpServer<Express.Request, Express.Response, Express>;

21

22

/** Start the application server */

23

listen(port: number | string, callback?: () => void): Promise<TServer>;

24

listen(

25

port: number | string,

26

hostname: string,

27

callback?: () => void

28

): Promise<TServer>;

29

30

/** Configure Express application settings */

31

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

32

33

/** Configure view template engine */

34

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

35

36

/** Enable Express features */

37

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

38

39

/** Disable Express features */

40

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

41

42

/** Serve static files from directory */

43

useStaticAssets(options: ServeStaticOptions): this;

44

useStaticAssets(path: string, options?: ServeStaticOptions): this;

45

46

/** Enable Cross-Origin Resource Sharing */

47

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

48

49

/** Configure Express body parser */

50

useBodyParser<Options = NestExpressBodyParserOptions>(

51

parser: NestExpressBodyParserType,

52

options?: Omit<Options, 'verify'>

53

): this;

54

55

/** Set view template directories */

56

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

57

58

/** Set view rendering engine */

59

setViewEngine(engine: string): this;

60

61

/** Set application-level template variables */

62

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

63

}

64

```

65

66

**Usage Examples:**

67

68

```typescript

69

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

70

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

71

72

// Create Express-based application

73

const app = await NestFactory.create<NestExpressApplication>(AppModule);

74

75

// Configure Express features

76

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

77

app.enable('case sensitive routing');

78

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

79

80

// Set up static files and templates

81

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

82

app.setBaseViewsDir('views');

83

app.setViewEngine('hbs');

84

85

// Configure CORS and body parsing

86

app.enableCors({ origin: 'https://example.com' });

87

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

88

89

await app.listen(3000);

90

```

91

92

### Static File Configuration

93

94

Configure static file serving with various options for caching, security, and URL handling.

95

96

```typescript { .api }

97

/**

98

* Options for serving static files with Express

99

* Controls caching, security, and file handling behavior

100

*/

101

interface ServeStaticOptions {

102

/** How to treat dotfiles: 'allow', 'deny', or 'ignore' */

103

dotfiles?: string;

104

105

/** Enable or disable etag generation */

106

etag?: boolean;

107

108

/** File extension fallbacks for requests without extensions */

109

extensions?: string[];

110

111

/** Enable directory fallthrough on file not found */

112

fallthrough?: boolean;

113

114

/** Enable immutable cache-control directive */

115

immutable?: boolean;

116

117

/** Directory index file configuration */

118

index?: boolean | string | string[];

119

120

/** Enable Last-Modified header */

121

lastModified?: boolean;

122

123

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

124

maxAge?: number | string;

125

126

/** Enable redirect for trailing slash on directories */

127

redirect?: boolean;

128

129

/** Function to set custom headers on responses */

130

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

131

132

/** URL prefix for serving static files */

133

prefix?: string;

134

}

135

```

136

137

**Usage Examples:**

138

139

```typescript

140

// Basic static file serving

141

app.useStaticAssets('public');

142

143

// Static files with prefix

144

app.useStaticAssets('uploads', { prefix: '/files/' });

145

146

// Advanced static file configuration

147

app.useStaticAssets('assets', {

148

maxAge: '1y',

149

etag: true,

150

immutable: true,

151

extensions: ['html', 'htm'],

152

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

153

if (path.endsWith('.js')) {

154

res.set('Content-Type', 'application/javascript');

155

}

156

}

157

});

158

159

// Multiple static directories

160

app.useStaticAssets('public');

161

app.useStaticAssets('uploads', { prefix: '/media/' });

162

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

163

```

164

165

### Body Parser Configuration

166

167

Configure Express body parsing with support for different content types and raw body access.

168

169

```typescript { .api }

170

/**

171

* Body parser types supported by Express

172

* Each type handles different content formats

173

*/

174

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

175

176

/**

177

* Configuration options for Express body parsers

178

* Supports various parsing limits and type filtering

179

*/

180

interface NestExpressBodyParserOptions {

181

/** Enable/disable gzip/deflate inflation of request body */

182

inflate?: boolean;

183

184

/** Request size limit (bytes, string with unit, or number) */

185

limit?: number | string;

186

187

/** Media type(s) to parse, string, array, or function */

188

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

189

190

/** Additional parser-specific options */

191

[key: string]: any;

192

}

193

```

194

195

**Usage Examples:**

196

197

```typescript

198

// Configure JSON parser

199

app.useBodyParser('json', {

200

limit: '10mb',

201

type: 'application/json'

202

});

203

204

// Configure URL-encoded parser

205

app.useBodyParser('urlencoded', {

206

limit: '5mb',

207

extended: true,

208

parameterLimit: 1000

209

});

210

211

// Configure text parser

212

app.useBodyParser('text', {

213

limit: '1mb',

214

type: 'text/*'

215

});

216

217

// Configure raw buffer parser

218

app.useBodyParser('raw', {

219

limit: '50mb',

220

type: 'application/octet-stream'

221

});

222

223

// Configure with custom type detection

224

app.useBodyParser('json', {

225

type: (req) => req.headers['content-type'] === 'application/vnd.api+json'

226

});

227

```

228

229

### Express Server Types

230

231

Type definitions for HTTP servers used with Express applications.

232

233

```typescript { .api }

234

import type { Server as CoreHttpServer } from 'http';

235

import type { Server as CoreHttpsServer } from 'https';

236

import type { Express } from 'express';

237

238

/** Generic server type that can be HTTP or HTTPS */

239

type ExpressServer = CoreHttpServer | CoreHttpsServer;

240

241

/** Express application instance type */

242

type ExpressInstance = Express;

243

```

244

245

### CORS Configuration

246

247

Types for Cross-Origin Resource Sharing configuration (imported from @nestjs/common).

248

249

```typescript { .api }

250

/** CORS configuration options */

251

interface CorsOptions {

252

/** Allowed origins */

253

origin?: boolean | string | RegExp | (string | RegExp)[] |

254

((origin: string, callback: (err: Error | null, allow?: boolean) => void) => void);

255

256

/** Allowed HTTP methods */

257

methods?: string | string[];

258

259

/** Allowed headers */

260

allowedHeaders?: string | string[];

261

262

/** Exposed headers */

263

exposedHeaders?: string | string[];

264

265

/** Allow credentials */

266

credentials?: boolean;

267

268

/** Max age for preflight cache */

269

maxAge?: number;

270

271

/** Enable preflight pass-through */

272

preflightContinue?: boolean;

273

274

/** Success status for OPTIONS requests */

275

optionsSuccessStatus?: number;

276

}

277

278

/** Dynamic CORS configuration function */

279

type CorsOptionsDelegate<T = any> = (

280

req: T,

281

callback: (err: Error | null, options?: CorsOptions) => void

282

) => void;

283

```

284

285

**Usage Examples:**

286

287

```typescript

288

// Simple CORS configuration

289

app.enableCors({

290

origin: 'https://example.com',

291

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

292

credentials: true

293

});

294

295

// Multiple origins

296

app.enableCors({

297

origin: [

298

'https://example.com',

299

'https://app.example.com',

300

/\.example\.com$/

301

]

302

});

303

304

// Dynamic CORS configuration

305

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

306

const corsOptions: CorsOptions = {

307

origin: req.headers.origin === 'https://trusted.com',

308

credentials: true

309

};

310

callback(null, corsOptions);

311

});

312

313

// Development vs production CORS

314

const corsOptions: CorsOptions = {

315

origin: process.env.NODE_ENV === 'development'

316

? true

317

: ['https://app.example.com'],

318

credentials: true,

319

optionsSuccessStatus: 200

320

};

321

app.enableCors(corsOptions);

322

```

323

324

### Application Lifecycle

325

326

Methods for managing application startup and HTTP server binding.

327

328

```typescript { .api }

329

/**

330

* Start the NestJS application server

331

* Returns a Promise that resolves to the underlying HTTP server

332

*/

333

listen(port: number | string, callback?: () => void): Promise<TServer>;

334

listen(

335

port: number | string,

336

hostname: string,

337

callback?: () => void

338

): Promise<TServer>;

339

```

340

341

**Usage Examples:**

342

343

```typescript

344

// Start server on port 3000

345

await app.listen(3000);

346

347

// Start with callback

348

await app.listen(3000, () => {

349

console.log('Application is running on http://localhost:3000');

350

});

351

352

// Start on specific hostname

353

await app.listen(3000, '0.0.0.0', () => {

354

console.log('Server started on all interfaces');

355

});

356

357

// Store server reference

358

const server = await app.listen(3000);

359

console.log('Server type:', server.constructor.name); // 'Server'

360

361

// Graceful shutdown

362

process.on('SIGTERM', async () => {

363

await app.close();

364

process.exit(0);

365

});

366

```