or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

decorators.mdfastify-adapter.mdindex.mdinterfaces.md

fastify-adapter.mddocs/

0

# HTTP Adapter

1

2

The FastifyAdapter class is the core component that integrates Fastify with NestJS, providing HTTP server functionality, lifecycle management, and middleware support.

3

4

## Capabilities

5

6

### FastifyAdapter Class

7

8

Main HTTP adapter that extends AbstractHttpAdapter and provides Fastify-specific functionality.

9

10

```typescript { .api }

11

/**

12

* Main HTTP adapter for integrating Fastify with NestJS

13

* Supports multiple server types (HTTP, HTTPS, HTTP2) with generic type parameters

14

*/

15

class FastifyAdapter<

16

TServer extends RawServerBase = RawServerDefault,

17

TRawRequest extends FastifyRawRequest<TServer> = FastifyRawRequest<TServer>,

18

TRawResponse extends RawReplyDefaultExpression<TServer> = RawReplyDefaultExpression<TServer>,

19

TRequest extends FastifyRequest<RequestGenericInterface, TServer, TRawRequest> = FastifyRequest<RequestGenericInterface, TServer, TRawRequest>,

20

TReply extends FastifyReply<RouteGenericInterface, TServer, TRawRequest, TRawResponse> = FastifyReply<RouteGenericInterface, TServer, TRawRequest, TRawResponse>,

21

TInstance extends FastifyInstance<TServer, TRawRequest, TRawResponse> = FastifyInstance<TServer, TRawRequest, TRawResponse>

22

> extends AbstractHttpAdapter<TServer, TRequest, TReply> {

23

constructor(

24

instanceOrOptions?:

25

| TInstance

26

| FastifyHttp2Options<any>

27

| FastifyHttp2SecureOptions<any>

28

| FastifyHttpsOptions<any>

29

| FastifyHttpOptions<any>

30

| FastifyAdapterBaseOptions<TServer>

31

);

32

}

33

```

34

35

**Usage Examples:**

36

37

```typescript

38

import { FastifyAdapter } from '@nestjs/platform-fastify';

39

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

40

41

// Basic adapter

42

const adapter = new FastifyAdapter();

43

44

// With options

45

const adapter = new FastifyAdapter({

46

logger: true,

47

bodyLimit: 1024 * 1024,

48

});

49

50

// With HTTPS

51

const adapter = new FastifyAdapter({

52

https: {

53

key: fs.readFileSync('server.key'),

54

cert: fs.readFileSync('server.cert')

55

}

56

});

57

58

// With HTTP2

59

const adapter = new FastifyAdapter({

60

http2: true,

61

https: {

62

key: fs.readFileSync('server.key'),

63

cert: fs.readFileSync('server.cert')

64

}

65

});

66

67

// Create NestJS app with adapter

68

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

69

```

70

71

### Lifecycle Management

72

73

Methods for managing the adapter lifecycle and hooks.

74

75

```typescript { .api }

76

/**

77

* Sets a hook that runs before each request

78

* @param hook - Function to execute on each request

79

*/

80

setOnRequestHook(

81

hook: (

82

request: TRequest,

83

reply: TReply,

84

done: (err?: Error) => void

85

) => void | Promise<void>

86

): void;

87

88

/**

89

* Sets a hook that runs after each response

90

* @param hook - Function to execute after each response

91

*/

92

setOnResponseHook(

93

hook: (

94

request: TRequest,

95

reply: TReply,

96

done: (err?: Error) => void

97

) => void | Promise<void>

98

): void;

99

100

/**

101

* Initializes the adapter and registers necessary middleware

102

* Must be called before starting the server

103

*/

104

init(): Promise<void>;

105

106

/**

107

* Closes the server and cleans up resources

108

*/

109

close(): Promise<void>;

110

```

111

112

### Server Operations

113

114

Methods for starting and managing the HTTP server.

115

116

```typescript { .api }

117

/**

118

* Starts the server listening on specified port

119

* @param port - Port number or string

120

* @param callback - Optional callback when server starts

121

*/

122

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

123

124

/**

125

* Starts the server with hostname specification

126

* @param port - Port number or string

127

* @param hostname - Hostname to bind to

128

* @param callback - Optional callback when server starts

129

*/

130

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

131

132

/**

133

* Starts the server with Fastify listen options

134

* @param listenOptions - Fastify listen configuration

135

* @param args - Additional arguments

136

*/

137

listen(listenOptions: string | number | FastifyListenOptions, ...args: any[]): void;

138

139

/**

140

* Returns the underlying HTTP server instance

141

*/

142

getHttpServer<T = TServer>(): T;

143

144

/**

145

* Returns the Fastify instance

146

*/

147

getInstance<T = TInstance>(): T;

148

149

/**

150

* Gets the adapter type identifier

151

*/

152

getType(): string; // Returns "fastify"

153

```

154

155

### Route Registration

156

157

Methods for registering HTTP route handlers with various HTTP methods.

158

159

```typescript { .api }

160

/**

161

* Registers a GET route handler

162

*/

163

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

164

165

/**

166

* Registers a POST route handler

167

*/

168

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

169

170

/**

171

* Registers a PUT route handler

172

*/

173

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

174

175

/**

176

* Registers a PATCH route handler

177

*/

178

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

179

180

/**

181

* Registers a DELETE route handler

182

*/

183

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

184

185

/**

186

* Registers a HEAD route handler

187

*/

188

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

189

190

/**

191

* Registers an OPTIONS route handler

192

*/

193

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

194

195

/**

196

* Registers a SEARCH route handler

197

*/

198

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

199

200

/**

201

* Registers a PROPFIND route handler (WebDAV)

202

*/

203

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

204

205

/**

206

* Registers a PROPPATCH route handler (WebDAV)

207

*/

208

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

209

210

/**

211

* Registers a MKCOL route handler (WebDAV)

212

*/

213

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

214

215

/**

216

* Registers a COPY route handler (WebDAV)

217

*/

218

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

219

220

/**

221

* Registers a MOVE route handler (WebDAV)

222

*/

223

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

224

225

/**

226

* Registers a LOCK route handler (WebDAV)

227

*/

228

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

229

230

/**

231

* Registers an UNLOCK route handler (WebDAV)

232

*/

233

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

234

```

235

236

### Response Handling

237

238

Methods for handling HTTP responses and status codes.

239

240

```typescript { .api }

241

/**

242

* Sends a response with optional status code

243

* @param response - Response object (raw or Fastify reply)

244

* @param body - Response body

245

* @param statusCode - Optional HTTP status code

246

*/

247

reply(response: TRawResponse | TReply, body: any, statusCode?: number): any;

248

249

/**

250

* Sets the response status code

251

* @param response - Response object

252

* @param statusCode - HTTP status code

253

*/

254

status(response: TRawResponse | TReply, statusCode: number): any;

255

256

/**

257

* Ends the response

258

* @param response - Response object

259

* @param message - Optional message to send

260

*/

261

end(response: TReply, message?: string): void;

262

263

/**

264

* Renders a view template

265

* @param response - Response object with view method

266

* @param view - View template name

267

* @param options - Template options

268

*/

269

render(response: TReply & { view: Function }, view: string, options: any): any;

270

271

/**

272

* Redirects the response

273

* @param response - Response object

274

* @param statusCode - Redirect status code

275

* @param url - Target URL

276

*/

277

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

278

```

279

280

### Header Management

281

282

Methods for managing HTTP headers.

283

284

```typescript { .api }

285

/**

286

* Checks if response headers have been sent

287

* @param response - Response object

288

*/

289

isHeadersSent(response: TReply): boolean;

290

291

/**

292

* Gets a response header value

293

* @param response - Response object

294

* @param name - Header name

295

*/

296

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

297

298

/**

299

* Sets a response header

300

* @param response - Response object

301

* @param name - Header name

302

* @param value - Header value

303

*/

304

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

305

306

/**

307

* Appends a value to a response header

308

* @param response - Response object

309

* @param name - Header name

310

* @param value - Header value to append

311

*/

312

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

313

```

314

315

### Request Information

316

317

Methods for extracting information from HTTP requests.

318

319

```typescript { .api }

320

/**

321

* Gets the request hostname

322

* @param request - Request object

323

*/

324

getRequestHostname(request: TRequest): string;

325

326

/**

327

* Gets the request HTTP method

328

* @param request - Request object

329

*/

330

getRequestMethod(request: TRequest): string;

331

332

/**

333

* Gets the request URL

334

* @param request - Request object

335

*/

336

getRequestUrl(request: TRequest): string;

337

getRequestUrl(request: TRawRequest): string;

338

```

339

340

### Plugin and Middleware Management

341

342

Methods for registering Fastify plugins and middleware.

343

344

```typescript { .api }

345

/**

346

* Registers a Fastify plugin

347

* @param plugin - Fastify plugin

348

* @param opts - Plugin options

349

*/

350

register<TRegister extends Parameters<FastifyRegister<FastifyInstance<TServer, TRawRequest, TRawResponse>>>>(

351

plugin: TRegister['0'],

352

opts?: TRegister['1']

353

): Promise<TInstance>;

354

355

/**

356

* Registers middleware (requires @fastify/middie)

357

* @param args - Middleware arguments

358

*/

359

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

360

361

/**

362

* Creates a middleware factory for specific request methods

363

* @param requestMethod - HTTP request method

364

*/

365

createMiddlewareFactory(requestMethod: RequestMethod): Promise<(path: string, callback: Function) => any>;

366

```

367

368

### Body Parsing

369

370

Methods for configuring request body parsing.

371

372

```typescript { .api }

373

/**

374

* Indicates if body parsers are registered

375

*/

376

readonly isParserRegistered: boolean;

377

378

/**

379

* Registers default body parsers (JSON and URL-encoded)

380

* @param prefix - Optional path prefix

381

* @param rawBody - Whether to preserve raw body

382

*/

383

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

384

385

/**

386

* Registers a custom body parser

387

* @param type - Content type to parse

388

* @param rawBody - Whether to preserve raw body

389

* @param options - Parser options

390

* @param parser - Custom parser function

391

*/

392

useBodyParser(

393

type: string | string[] | RegExp,

394

rawBody: boolean,

395

options?: NestFastifyBodyParserOptions,

396

parser?: FastifyBodyParser<Buffer, TServer>

397

): void;

398

```

399

400

### Static Assets and View Engine

401

402

Methods for serving static files and configuring template engines.

403

404

```typescript { .api }

405

/**

406

* Configures static asset serving

407

* @param options - Static asset configuration

408

*/

409

useStaticAssets(options: FastifyStaticOptions): Promise<TInstance>;

410

411

/**

412

* Configures the view engine for template rendering

413

* @param options - View engine configuration

414

*/

415

setViewEngine(options: FastifyViewOptions | string): Promise<TInstance>;

416

```

417

418

### CORS Support

419

420

Method for enabling Cross-Origin Resource Sharing.

421

422

```typescript { .api }

423

/**

424

* Enables CORS with optional configuration

425

* @param options - CORS configuration options

426

*/

427

enableCors(options?: FastifyCorsOptions): void;

428

```

429

430

### Error Handling

431

432

Methods for configuring error and not found handlers.

433

434

```typescript { .api }

435

/**

436

* Sets a global error handler

437

* @param handler - Error handling function

438

*/

439

setErrorHandler(handler: Parameters<TInstance['setErrorHandler']>[0]): any;

440

441

/**

442

* Sets a handler for 404 not found responses

443

* @param handler - Not found handling function

444

*/

445

setNotFoundHandler(handler: Function): any;

446

```

447

448

### Testing Support

449

450

Method for injecting test requests.

451

452

```typescript { .api }

453

/**

454

* Injects a test request (returns chain for building request)

455

*/

456

inject(): LightMyRequestChain;

457

458

/**

459

* Injects a test request with options

460

* @param opts - Request options or URL string

461

*/

462

inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>;

463

```

464

465

### API Versioning

466

467

Method for applying version filters to route handlers.

468

469

```typescript { .api }

470

/**

471

* Applies version filtering to a route handler

472

* @param handler - Route handler function

473

* @param version - API version specification

474

* @param versioningOptions - Versioning configuration

475

*/

476

applyVersionFilter(

477

handler: Function,

478

version: VersionValue,

479

versioningOptions: VersioningOptions

480

): VersionedRoute<TRequest, TReply>;

481

```

482

483

## Constructor Options Types

484

485

### Base Options

486

487

```typescript { .api }

488

interface FastifyAdapterBaseOptions<

489

Server extends RawServerBase = RawServerDefault,

490

Logger extends FastifyBaseLogger = FastifyBaseLogger

491

> extends FastifyServerOptions<Server, Logger> {

492

/** Skip automatic registration of @fastify/middie middleware plugin */

493

skipMiddie?: boolean;

494

}

495

```

496

497

### HTTP2 Secure Options

498

499

```typescript { .api }

500

interface FastifyHttp2SecureOptions<

501

Server extends http2.Http2SecureServer,

502

Logger extends FastifyBaseLogger = FastifyBaseLogger

503

> extends FastifyAdapterBaseOptions<Server, Logger> {

504

http2: true;

505

https: http2.SecureServerOptions;

506

}

507

```

508

509

### HTTP2 Options

510

511

```typescript { .api }

512

interface FastifyHttp2Options<

513

Server extends http2.Http2Server,

514

Logger extends FastifyBaseLogger = FastifyBaseLogger

515

> extends FastifyAdapterBaseOptions<Server, Logger> {

516

http2: true;

517

http2SessionTimeout?: number;

518

}

519

```

520

521

### HTTPS Options

522

523

```typescript { .api }

524

interface FastifyHttpsOptions<

525

Server extends https.Server,

526

Logger extends FastifyBaseLogger = FastifyBaseLogger

527

> extends FastifyAdapterBaseOptions<Server, Logger> {

528

https: https.ServerOptions;

529

}

530

```

531

532

### HTTP Options

533

534

```typescript { .api }

535

interface FastifyHttpOptions<

536

Server extends http.Server,

537

Logger extends FastifyBaseLogger = FastifyBaseLogger

538

> extends FastifyAdapterBaseOptions<Server, Logger> {

539

http: http.ServerOptions;

540

}

541

```