nestjs-boost 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +68 -0
- package/LICENSE +21 -0
- package/NOTICE.md +6 -0
- package/README.md +168 -2
- package/bin/nestjs-boost.mjs +148 -0
- package/guidelines/core.md +64 -0
- package/lib/agents.mjs +137 -0
- package/lib/installer.mjs +450 -0
- package/lib/prompt.mjs +131 -0
- package/lib/setup.mjs +60 -0
- package/manifest.json +676 -0
- package/package.json +67 -6
- package/scripts/postinstall.mjs +49 -0
- package/skills/nestjs-ai/SKILL.md +145 -0
- package/skills/nestjs-ai/references/ai-reference.md +143 -0
- package/skills/nestjs-architecture/SKILL.md +83 -0
- package/skills/nestjs-architecture/references/dynamic-modules.md +92 -0
- package/skills/nestjs-architecture/references/scopes-lifecycle.md +98 -0
- package/skills/nestjs-architecture/references/troubleshooting.md +77 -0
- package/skills/nestjs-authentication/SKILL.md +115 -0
- package/skills/nestjs-authentication/references/flows.md +180 -0
- package/skills/nestjs-authorization/SKILL.md +104 -0
- package/skills/nestjs-caching/SKILL.md +109 -0
- package/skills/nestjs-cli-tooling/SKILL.md +94 -0
- package/skills/nestjs-cli-tooling/references/nest-cli-json.md +91 -0
- package/skills/nestjs-configuration/SKILL.md +109 -0
- package/skills/nestjs-cqrs/SKILL.md +124 -0
- package/skills/nestjs-database-drizzle/SKILL.md +117 -0
- package/skills/nestjs-database-mikro-orm/SKILL.md +109 -0
- package/skills/nestjs-database-mongoose/SKILL.md +124 -0
- package/skills/nestjs-database-prisma/SKILL.md +126 -0
- package/skills/nestjs-database-sequelize/SKILL.md +88 -0
- package/skills/nestjs-database-typeorm/SKILL.md +110 -0
- package/skills/nestjs-deployment/SKILL.md +133 -0
- package/skills/nestjs-deployment/references/serverless-and-systemd.md +133 -0
- package/skills/nestjs-events/SKILL.md +78 -0
- package/skills/nestjs-file-storage/SKILL.md +111 -0
- package/skills/nestjs-file-storage/references/storage-reference.md +82 -0
- package/skills/nestjs-graphql/SKILL.md +119 -0
- package/skills/nestjs-graphql/references/federation.md +110 -0
- package/skills/nestjs-graphql/references/schema-features.md +133 -0
- package/skills/nestjs-health-checks/SKILL.md +114 -0
- package/skills/nestjs-http-client/SKILL.md +118 -0
- package/skills/nestjs-http-client/references/http-client-reference.md +116 -0
- package/skills/nestjs-http-platform/SKILL.md +104 -0
- package/skills/nestjs-http-platform/references/adapters.md +88 -0
- package/skills/nestjs-http-web-features/SKILL.md +113 -0
- package/skills/nestjs-http-web-features/references/uploads-streaming.md +108 -0
- package/skills/nestjs-i18n/SKILL.md +113 -0
- package/skills/nestjs-idempotency/SKILL.md +112 -0
- package/skills/nestjs-locks/SKILL.md +108 -0
- package/skills/nestjs-logging/SKILL.md +123 -0
- package/skills/nestjs-mail/SKILL.md +125 -0
- package/skills/nestjs-mail/references/mail-reference.md +90 -0
- package/skills/nestjs-mcp-server/SKILL.md +152 -0
- package/skills/nestjs-mcp-server/references/mcp-reference.md +146 -0
- package/skills/nestjs-microservices/SKILL.md +108 -0
- package/skills/nestjs-microservices/references/transports.md +117 -0
- package/skills/nestjs-observability/SKILL.md +108 -0
- package/skills/nestjs-observability/references/apm-and-otel.md +106 -0
- package/skills/nestjs-openapi/SKILL.md +90 -0
- package/skills/nestjs-openapi/references/swagger-reference.md +180 -0
- package/skills/nestjs-outbox/SKILL.md +119 -0
- package/skills/nestjs-outbox/references/outbox-reference.md +74 -0
- package/skills/nestjs-passport-auth/SKILL.md +125 -0
- package/skills/nestjs-queues/SKILL.md +118 -0
- package/skills/nestjs-queues/references/bull-legacy.md +75 -0
- package/skills/nestjs-request-pipeline/SKILL.md +146 -0
- package/skills/nestjs-request-pipeline/references/filters-interceptors.md +114 -0
- package/skills/nestjs-request-pipeline/references/pipes-decorators.md +80 -0
- package/skills/nestjs-resilience/SKILL.md +116 -0
- package/skills/nestjs-resilience/references/resilience-reference.md +74 -0
- package/skills/nestjs-scheduling/SKILL.md +100 -0
- package/skills/nestjs-security-hardening/SKILL.md +99 -0
- package/skills/nestjs-security-hardening/references/throttler-advanced.md +78 -0
- package/skills/nestjs-standalone-apps/SKILL.md +78 -0
- package/skills/nestjs-testing/SKILL.md +118 -0
- package/skills/nestjs-testing/references/advanced-testing.md +62 -0
- package/skills/nestjs-upgrading/SKILL.md +82 -0
- package/skills/nestjs-upgrading/references/esm-switch.md +114 -0
- package/skills/nestjs-validation-serialization/SKILL.md +124 -0
- package/skills/nestjs-validation-serialization/references/validation-options.md +84 -0
- package/skills/nestjs-webhooks/SKILL.md +116 -0
- package/skills/nestjs-webhooks/references/webhooks-reference.md +132 -0
- package/skills/nestjs-websockets/SKILL.md +108 -0
- package/skills/nestjs-workflows/SKILL.md +123 -0
- package/skills/nestjs-workflows/references/workflows-reference.md +85 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-openapi
|
|
3
|
+
description: Documents NestJS 12 HTTP APIs with @nestjs/swagger — SwaggerModule and DocumentBuilder setup with a lazy document factory, Swagger UI and JSON/YAML endpoints, @ApiProperty/@ApiBody/@ApiQuery/@ApiParam/@ApiResponse decorators, Standard Schema (Zod, Valibot) bodies converted to OpenAPI, enums, generics, oneOf/allOf, security schemes (bearer, basic, OAuth2, cookie), tags, file uploads, mapped types from @nestjs/swagger, the Swagger CLI plugin (comments introspection, SWC metadata), global parameters and responses, multiple specifications and OpenAPI 3.2 tags. Use when adding Swagger/OpenAPI docs, fixing missing or wrong schemas in the generated spec, exporting openapi.json for client generation, documenting auth, or when Swagger UI is blank/blocked by CSP. Not for GraphQL schemas (nestjs-graphql) or request validation itself (nestjs-validation-serialization).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/swagger; @fastify/static on Fastify; zod 4.2+ converts natively
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS OpenAPI (Swagger)
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm i @nestjs/swagger # Fastify: also npm i @fastify/static
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Setup
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
// main.ts — after app.enableVersioning() / setGlobalPrefix()
|
|
21
|
+
const config = new DocumentBuilder()
|
|
22
|
+
.setTitle('Store API').setDescription('Public API').setVersion('1.0')
|
|
23
|
+
.addBearerAuth()
|
|
24
|
+
.build();
|
|
25
|
+
const documentFactory = () => SwaggerModule.createDocument(app, config); // lazy: built on first request
|
|
26
|
+
SwaggerModule.setup('api', app, documentFactory, { jsonDocumentUrl: 'api/json' });
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- UI at `/api`, JSON at `/api-json` (or `jsonDocumentUrl`), YAML at `/api-yaml`. `ui: false` keeps raw definitions; `raw: []` keeps the UI only.
|
|
30
|
+
- Eager `createDocument()` must run after `enableVersioning()`, or paths lose the version prefix.
|
|
31
|
+
- Built-in `app.useSecurityHeaders()` CSP works with Swagger UI; prefer it. A Fastify `helmet` CSP needs `'unsafe-inline'` styles/scripts and `data:` images, which weakens XSS protection app-wide: relax it only when docs are enabled (not in production), and never allow bare `https:` (see reference).
|
|
32
|
+
- Gate docs in production if they shouldn't be public (only call `setup()` when enabled by config).
|
|
33
|
+
|
|
34
|
+
## Describing models: pick one approach per project
|
|
35
|
+
|
|
36
|
+
| Project validates with | Do this |
|
|
37
|
+
| --- | --- |
|
|
38
|
+
| class-validator DTOs | Enable the **CLI plugin** (`"plugins": ["@nestjs/swagger"]` in `nest-cli.json`) so `@ApiProperty()` is inferred from types, `?` and validator decorators; add `@ApiProperty()` only to override. Import `PartialType`/`PickType`/`OmitType`/`IntersectionType` from `@nestjs/swagger`, not `@nestjs/mapped-types` |
|
|
39
|
+
| Standard Schema (`@Body({ schema })`) | Nothing for Zod ≥4.2 (exposes `~standard.jsonSchema`). Other libraries: `standardSchemaConverter` in `SwaggerDocumentOptions` (zod-openapi, `@valibot/to-json-schema`), branching on `~standard.vendor` |
|
|
40
|
+
| No plugin, plain classes | `@ApiProperty()` / `@ApiPropertyOptional()` on every property |
|
|
41
|
+
|
|
42
|
+
TypeScript erases generics and interfaces: arrays of DTOs in bodies need `@ApiBody({ type: [CreateUserDto] })`; arrays in properties need `type: [String]` without the plugin; circular refs need `type: () => Node`.
|
|
43
|
+
|
|
44
|
+
## Operations
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
@ApiTags('orders')
|
|
48
|
+
@ApiBearerAuth()
|
|
49
|
+
@Controller('orders')
|
|
50
|
+
export class OrdersController {
|
|
51
|
+
@Post()
|
|
52
|
+
@ApiOperation({ summary: 'Place an order' })
|
|
53
|
+
@ApiCreatedResponse({ type: OrderDto })
|
|
54
|
+
@ApiBadRequestResponse({ description: 'Validation failed' })
|
|
55
|
+
create(@Body() dto: CreateOrderDto) {}
|
|
56
|
+
|
|
57
|
+
@Get()
|
|
58
|
+
@ApiQuery({ name: 'status', enum: OrderStatus, enumName: 'OrderStatus', required: false })
|
|
59
|
+
@ApiOkResponse({ type: [OrderDto] })
|
|
60
|
+
findAll(@Query('status') status?: OrderStatus) {}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
- Shorthand response decorators exist for every common status (`@ApiOkResponse`, `@ApiNotFoundResponse`, `@ApiTooManyRequestsResponse`, … `@ApiDefaultResponse`).
|
|
65
|
+
- Enums: add `enumName` so a reusable schema is generated instead of inline values.
|
|
66
|
+
- Uploads: `@ApiConsumes('multipart/form-data')` + `@ApiBody` with `format: 'binary'` (see reference).
|
|
67
|
+
- Security: `addBearerAuth()` / `addBasicAuth()` / `addOAuth2()` / `addCookieAuth('sid')` in the builder, and the matching `@ApiBearerAuth()` / `@ApiBasicAuth()` / `@ApiOAuth2(['scope'])` / `@ApiCookieAuth()` on controllers or routes.
|
|
68
|
+
- Hide: `@ApiExcludeController()`, `@ApiExcludeEndpoint()`, `@ApiHideProperty()`. Rename a schema: `@ApiSchema({ name: 'CreateCatRequest' })`.
|
|
69
|
+
- Every route on the docs and generated clients uses `operationId` = `Controller_method`; customize with `operationIdFactory`.
|
|
70
|
+
|
|
71
|
+
## Plugin gotchas
|
|
72
|
+
|
|
73
|
+
- The plugin runs only through the Nest CLI compiler. With SWC: `nest start -b swc --type-check`; monorepos generate `metadata.ts` with `PluginMetadataGenerator` and call `await SwaggerModule.loadPluginMetadata(metadata)` before `createDocument()`.
|
|
74
|
+
- Test runners compile in memory without the plugin: for ts-jest add the `@nestjs/swagger/plugin` AST transformer (reference), or assert on the spec in a build-based test.
|
|
75
|
+
- `introspectComments: true` turns JSDoc into descriptions/summaries.
|
|
76
|
+
- The plugin documents but does not validate: keep the class-validator decorators.
|
|
77
|
+
|
|
78
|
+
## Workflow
|
|
79
|
+
|
|
80
|
+
- [ ] 1. Install; add the builder + lazy factory to `main.ts` after prefix/versioning.
|
|
81
|
+
- [ ] 2. Choose the model approach from the table; enable the CLI plugin for DTO projects.
|
|
82
|
+
- [ ] 3. Add tags, auth schemes, response types and enum names; hide internal routes.
|
|
83
|
+
- [ ] 4. Add an e2e test that GETs `/api-json` and checks a path and schema exist (or write the document to `openapi.json` in CI for client generation).
|
|
84
|
+
- [ ] 5. Build, lint, run tests, start the app and open `/api`.
|
|
85
|
+
|
|
86
|
+
## Reference files
|
|
87
|
+
|
|
88
|
+
- `references/swagger-reference.md`: document and setup options, security schemes, file upload schema, generic paginated responses, oneOf/getSchemaPath/extra models, global parameters/responses, multiple specs and dropdown, OpenAPI 3.2 tags, plugin options and ts-jest transformer, Fastify CSP. Read when going beyond the basics above.
|
|
89
|
+
|
|
90
|
+
Sources: [Introduction](https://docs.nestjs.com/openapi/introduction) · [Types and parameters](https://docs.nestjs.com/openapi/types-and-parameters) · [Operations](https://docs.nestjs.com/openapi/operations) · [Security](https://docs.nestjs.com/openapi/security) · [Mapped types](https://docs.nestjs.com/openapi/mapped-types) · [Decorators](https://docs.nestjs.com/openapi/decorators) · [CLI plugin](https://docs.nestjs.com/openapi/cli-plugin) · [Other features](https://docs.nestjs.com/openapi/other-features)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# @nestjs/swagger reference
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
- Document options
|
|
5
|
+
- Setup options
|
|
6
|
+
- Security schemes
|
|
7
|
+
- File uploads
|
|
8
|
+
- Composition: oneOf, extra models, generic responses
|
|
9
|
+
- Enums, examples, raw definitions
|
|
10
|
+
- Global parameters and responses
|
|
11
|
+
- Multiple specifications
|
|
12
|
+
- OpenAPI 3.2 tags
|
|
13
|
+
- CLI plugin options and test integration
|
|
14
|
+
- Fastify helmet CSP
|
|
15
|
+
|
|
16
|
+
## Document options
|
|
17
|
+
|
|
18
|
+
`SwaggerModule.createDocument(app, config, options: SwaggerDocumentOptions)`:
|
|
19
|
+
|
|
20
|
+
| Option | Purpose |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| `include` | Modules to include (multiple specs) |
|
|
23
|
+
| `deepScanRoutes` | Also scan modules imported by `include` modules |
|
|
24
|
+
| `extraModels` | Models not referenced by any route |
|
|
25
|
+
| `ignoreGlobalPrefix` | Ignore `setGlobalPrefix()` |
|
|
26
|
+
| `operationIdFactory(controllerKey, methodKey, version)` | Custom `operationId` (default `Controller_method[_version]`) |
|
|
27
|
+
| `linkNameFactory` | Names for response `links` |
|
|
28
|
+
| `autoTagControllers` | Tag by controller name (default `true`) |
|
|
29
|
+
| `onlyIncludeDecoratedEndpoints` | Only routes with `@ApiIncludeEndpoint()` |
|
|
30
|
+
| `excludeDynamicDefaults` | Drop non-plain runtime defaults (e.g. `new Date()`) so the doc is stable |
|
|
31
|
+
| `standardSchemaConverter(schema, { schemaType })` | Convert Standard Schemas; return `undefined` to fall back |
|
|
32
|
+
|
|
33
|
+
Standard Schema converters:
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
standardSchemaConverter: (schema, { schemaType }) => {
|
|
37
|
+
if (hasVendor(schema, 'zod')) {
|
|
38
|
+
const converted = createSchema(schema as never, { io: schemaType, openapiVersion: '3.0.0' }); // zod-openapi
|
|
39
|
+
return { schema: converted.schema, components: converted.components };
|
|
40
|
+
}
|
|
41
|
+
if (hasVendor(schema, 'valibot')) {
|
|
42
|
+
return { schema: toJsonSchema(schema as never, { target: 'openapi-3.0', typeMode: schemaType }) }; // @valibot/to-json-schema
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
},
|
|
46
|
+
// hasVendor = (s, v) => (s as any)?.['~standard']?.vendor === v
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Always narrow by vendor; passing the wrong library's schema throws at generation time. Pass `schemaType` through (input = what clients send, output = after parsing).
|
|
50
|
+
|
|
51
|
+
## Setup options
|
|
52
|
+
|
|
53
|
+
`SwaggerModule.setup(path, app, documentOrFactory, options: SwaggerCustomOptions)`: `useGlobalPrefix`, `ui` (replaces deprecated `swaggerUiEnabled`), `raw` (`true | false | ['json' | 'yaml']`), `swaggerUrl`, `jsonDocumentUrl`, `yamlDocumentUrl`, `patchDocumentOnRequest(req, res, doc)` (per-request edits, e.g. hide admin paths), `explorer`, `swaggerOptions` (Swagger UI options such as `persistAuthorization`, `urls`), `customCss`, `customCssUrl`, `customJs`, `customJsStr`, `customfavIcon`, `customSiteTitle`.
|
|
54
|
+
|
|
55
|
+
## Security schemes
|
|
56
|
+
|
|
57
|
+
| Builder | Decorator |
|
|
58
|
+
| --- | --- |
|
|
59
|
+
| `addBasicAuth()` | `@ApiBasicAuth()` |
|
|
60
|
+
| `addBearerAuth()` | `@ApiBearerAuth()` |
|
|
61
|
+
| `addOAuth2()` | `@ApiOAuth2(['pets:write'])` |
|
|
62
|
+
| `addCookieAuth('optional-session-id')` | `@ApiCookieAuth()` |
|
|
63
|
+
| `addSecurity('name', scheme)` | `@ApiSecurity('name')` |
|
|
64
|
+
|
|
65
|
+
`@nestjs/authentication` sessions use the `__Host-sid` cookie by default: `addCookieAuth('__Host-sid')`.
|
|
66
|
+
|
|
67
|
+
## File uploads
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
class FileUploadDto { @ApiProperty({ type: 'string', format: 'binary' }) file: any; }
|
|
71
|
+
class FilesUploadDto { @ApiProperty({ type: 'array', items: { type: 'string', format: 'binary' } }) files: any[]; }
|
|
72
|
+
|
|
73
|
+
@UseInterceptors(FileInterceptor('file'))
|
|
74
|
+
@ApiConsumes('multipart/form-data')
|
|
75
|
+
@ApiBody({ description: 'Avatar', type: FileUploadDto })
|
|
76
|
+
upload(@UploadedFile() file: Express.Multer.File) {}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Composition: oneOf, extra models, generic responses
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
@ApiExtraModels(Cat, Dog, PaginatedDto)
|
|
83
|
+
@Controller('pets')
|
|
84
|
+
export class PetsController {
|
|
85
|
+
@ApiOkResponse({
|
|
86
|
+
schema: {
|
|
87
|
+
allOf: [
|
|
88
|
+
{ $ref: getSchemaPath(PaginatedDto) },
|
|
89
|
+
{ properties: { results: { type: 'array', items: { $ref: getSchemaPath(CatDto) } } } },
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
findAll() {}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
@ApiProperty({ oneOf: [{ $ref: getSchemaPath(Cat) }, { $ref: getSchemaPath(Dog) }] }) pet: Cat | Dog;
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Wrap the paginated pattern in a reusable decorator with `applyDecorators(ApiExtraModels(PaginatedDto, model), ApiOkResponse({ schema: … }))` taking `model: Type<any>`.
|
|
100
|
+
|
|
101
|
+
## Enums, examples, raw definitions
|
|
102
|
+
|
|
103
|
+
- `@ApiProperty({ enum: Role, enumName: 'Role', isArray: true })`; `@ApiQuery`/`@ApiParam` accept `enumName` too. Plugin `autoFillEnumName` fills it.
|
|
104
|
+
- Examples: `@ApiProperty({ example: 'Kitty' })` or `examples: { a: { value: … } }`.
|
|
105
|
+
- Raw: `@ApiProperty({ type: 'array', items: { type: 'array', items: { type: 'number' } } })` for nested arrays.
|
|
106
|
+
- Circular: `@ApiProperty({ type: () => Node })`.
|
|
107
|
+
|
|
108
|
+
## Global parameters and responses
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
new DocumentBuilder()
|
|
112
|
+
.addGlobalParameters({ name: 'tenantId', in: 'header' })
|
|
113
|
+
.addGlobalResponse({ status: 500, description: 'Internal server error' })
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Multiple specifications
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
SwaggerModule.setup('api/cats', app, () => SwaggerModule.createDocument(app, catsConfig, { include: [CatsModule] }));
|
|
120
|
+
SwaggerModule.setup('api/dogs', app, () => SwaggerModule.createDocument(app, dogsConfig, { include: [DogsModule] }));
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Dropdown in one UI: `explorer: true` and `swaggerOptions.urls: [{ name: 'Cats', url: 'api/cats/json' }, …]` pointing at each spec's JSON (`jsonDocumentUrl`).
|
|
124
|
+
|
|
125
|
+
## OpenAPI 3.2 tags
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
new DocumentBuilder()
|
|
129
|
+
.setOpenAPIVersion('3.2.0')
|
|
130
|
+
.addTag('Animals', 'Everything about animals', undefined, { kind: 'nav' })
|
|
131
|
+
.addTag('Cats', 'Cat operations', undefined, { parent: 'Animals' })
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`parent`/`kind`/`summary` require `setOpenAPIVersion('3.2.0')` and only work via `addTag()` (`@ApiTags()` ignores them).
|
|
135
|
+
|
|
136
|
+
## CLI plugin options and test integration
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{ "compilerOptions": { "plugins": [{ "name": "@nestjs/swagger", "options": { "introspectComments": true, "classValidatorShim": true } }] } }
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Options: `dtoFileNameSuffix` (`['.dto.ts', '.entity.ts']`), `controllerFileNameSuffix` (`['.controller.ts']`), `classValidatorShim` (true), `classTransformerShim` (false | true | `'exclusive'`), `dtoKeyOfComment` (`'description'`), `controllerKeyOfComment` (`'summary'`), `introspectComments` (false), `skipAutoHttpCode`, `skipDefaultValues`, `autoFillEnumName`, `esmCompatible` (detected per file).
|
|
143
|
+
|
|
144
|
+
Only files matching the suffixes are processed: name DTO files `*.dto.ts`.
|
|
145
|
+
|
|
146
|
+
ts-jest e2e: create a transformer file
|
|
147
|
+
|
|
148
|
+
```javascript
|
|
149
|
+
const transformer = require('@nestjs/swagger/plugin');
|
|
150
|
+
module.exports.name = 'nestjs-swagger-transformer';
|
|
151
|
+
module.exports.version = 1; // bump when options change
|
|
152
|
+
module.exports.factory = (cs) => transformer.before({}, cs.program);
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
and reference it in `transform: { '^.+\\.(t|j)s$': ['ts-jest', { astTransformers: { before: ['<path>'] } }] }` (jest 29+). Clear the jest cache after changes.
|
|
156
|
+
|
|
157
|
+
SWC: `nest start -b swc --type-check`; monorepo: `PluginMetadataGenerator` → `metadata.ts`, then `await SwaggerModule.loadPluginMetadata(metadata)`.
|
|
158
|
+
|
|
159
|
+
## Fastify helmet CSP
|
|
160
|
+
|
|
161
|
+
Prefer Nest's built-in `app.useSecurityHeaders()`: it already works with Swagger UI, so no CSP needs relaxing.
|
|
162
|
+
|
|
163
|
+
If you register `@fastify/helmet` yourself, Swagger UI needs inline scripts and styles. **This weakens XSS protection for every route, not just the docs**, so only do it when the docs are served (typically not in production), and never copy it into an API-only app:
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
if (config.get('SWAGGER_ENABLED') === 'true') { // docs off in production
|
|
167
|
+
await app.register(helmet, {
|
|
168
|
+
contentSecurityPolicy: {
|
|
169
|
+
directives: {
|
|
170
|
+
defaultSrc: [`'self'`],
|
|
171
|
+
styleSrc: [`'self'`, `'unsafe-inline'`],
|
|
172
|
+
imgSrc: [`'self'`, 'data:', 'validator.swagger.io'],
|
|
173
|
+
scriptSrc: [`'self'`, `'unsafe-inline'`], // add a specific CDN origin only if you load Swagger UI from one; never bare `https:`
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
} else {
|
|
178
|
+
await app.register(helmet); // default strict CSP
|
|
179
|
+
}
|
|
180
|
+
```
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-outbox
|
|
3
|
+
description: Publishes events reliably from NestJS 12 with the first-party transactional outbox package @nestjs/outbox — OutboxModule.forRoot/forRootAsync with a PostgresOutboxStore or MySqlOutboxStore and migrations, Outbox.add(tx, message) in the same transaction as your data, keys for per-entity ordering, delays, the relay (polling, leases, publishTimeout, notify), in-process @OnOutboxMessage handlers with per-consumer inboxes and processInTransaction for exactly-once writes, ClientProxyTransport to microservices, retries with backoff, NonRetryableMessageError and the dead-letter queue (list, requeue, purge), events and stats, and testing with PGlite and relay.runOnce(). Use when an event, message, email or webhook must be sent if and only if a database transaction commits (the dual-write problem), when replacing emit-after-save code, or when adding retries/dead letters for outgoing messages. Not for in-memory events (nestjs-events), job queues (nestjs-queues) or webhooks specifics (nestjs-webhooks builds on this).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/outbox; PostgreSQL (READ COMMITTED) or MySQL 8.4/9.x
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS transactional outbox (@nestjs/outbox)
|
|
12
|
+
|
|
13
|
+
`ClientProxy.emit()`, `EventEmitter2` and the CQRS `EventBus` publish from memory: save-then-publish loses events on crashes, publish-then-save announces things that never happened. The outbox makes the message a row in your transaction and relays it afterwards (at least once; inboxes dedupe).
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i @nestjs/outbox
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Register (with a store on your database)
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
OutboxModule.forRootAsync({
|
|
23
|
+
imports: [ClientsModule.registerAsync([{ name: ANALYTICS_SERVICE, useFactory: () => ({ transport: Transport.TCP, options: { host, port } }) }])],
|
|
24
|
+
transports: { analytics: ClientProxyTransport(ANALYTICS_SERVICE) }, // classes beside useFactory
|
|
25
|
+
useFactory: () => ({
|
|
26
|
+
route: (m) => (m.topic.startsWith('analytics.') ? 'analytics' : 'local'), // exactly one transport per message
|
|
27
|
+
relay: { enabled: process.env.OUTBOX_RELAY !== 'off', pollInterval: '1s', lease: '30s', publishTimeout: '10s' },
|
|
28
|
+
retry: { attempts: 10, backoff: { delay: '1s', maxDelay: '1m' } },
|
|
29
|
+
}),
|
|
30
|
+
}),
|
|
31
|
+
// providers of AppModule:
|
|
32
|
+
{ provide: PostgresOutboxStore, inject: [getDrizzleToken(), OutboxStorage],
|
|
33
|
+
useFactory: (db, storage: OutboxStorage) => new PostgresOutboxStore({ executor: fromDrizzle(db) }, storage) },
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- The store creates and migrates its own schema (`nest_outbox`). With `NODE_ENV=production` it doesn't auto-migrate (run `npx @nestjs/outbox migrate`, check `status` in CI) and startup fails without a store. The in-memory store **can't join transactions** (it warns) — never rely on it.
|
|
37
|
+
- Executors: `fromDrizzle(db)`, `fromTypeOrm(dataSource)`, `fromPrisma(prisma)` (driver adapter), `fromKysely(db)`, `fromPg(pool)`, `fromMysql2(pool)` — from `@nestjs/outbox/postgres` or `/mysql`.
|
|
38
|
+
- Global services: `Outbox`, `OutboxRelay`, `OutboxEvents`, `OutboxDeadLetters`, `OutboxInbox`, `OutboxStorage`.
|
|
39
|
+
|
|
40
|
+
## Add messages in the transaction
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
constructor(@InjectDrizzle() private readonly db: Database, private readonly outbox: Outbox<Transaction>) {}
|
|
44
|
+
|
|
45
|
+
const order = await this.db.transaction(async (tx) => {
|
|
46
|
+
await tx.insert(orders).values(order);
|
|
47
|
+
await this.outbox.add(tx, [
|
|
48
|
+
{ topic: 'order.placed', payload: order }, // in-process handlers (local)
|
|
49
|
+
{ topic: 'analytics.order.placed', key: order.id, payload: order }, // ordered per order
|
|
50
|
+
]);
|
|
51
|
+
return order;
|
|
52
|
+
});
|
|
53
|
+
this.outbox.notify(); // publish now, not at next poll
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
- Pass the **transaction** (Drizzle `tx`, TypeORM `EntityManager`, Prisma tx client) — the database itself is refused (`OutboxTransactionRequiredError`).
|
|
57
|
+
- Fields: `topic`, `payload` (snapshotted as JSON), optional `key` (ordering within the key, commit order), `headers`, `id` (UUIDv7 default), `delay` or `availableAt`.
|
|
58
|
+
- One message per destination. Don't share a key across transports (a failing destination would hold the others back).
|
|
59
|
+
- Keep these transactions short (per-key lock); retry MySQL deadlocks (1213).
|
|
60
|
+
|
|
61
|
+
## Handle messages
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
@Injectable()
|
|
65
|
+
export class OrderEmailsHandler { // singleton provider
|
|
66
|
+
@OnOutboxMessage('order.placed', { consumer: 'order-confirmation-email' }) // stable consumer name = inbox
|
|
67
|
+
async send(order: Order, { signal }: OutboxHandlerContext) { await this.mailer.sendConfirmation(order, { signal }); }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
@OnOutboxMessage('order.placed', { consumer: 'stock-reservation' })
|
|
71
|
+
async reserve(order: Order, ctx: OutboxHandlerContext<Transaction>) {
|
|
72
|
+
await this.db.transaction((tx) => ctx.processInTransaction(tx, async () => { /* writes via tx */ })); // exactly once for same-DB writes
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
| Handler | Guarantee |
|
|
77
|
+
| --- | --- |
|
|
78
|
+
| default inbox | once, unless crash between handler and inbox record |
|
|
79
|
+
| `ctx.processInTransaction(tx, work)` | exactly once for writes in the same database |
|
|
80
|
+
| `inbox: false` | at least once |
|
|
81
|
+
|
|
82
|
+
- Throw to retry (backoff, then dead letter `exhausted`); throw `NonRetryableMessageError` to dead-letter at once (`rejected`), e.g. permanent mail errors.
|
|
83
|
+
- Pass `ctx.signal`; handlers slower than `publishTimeout` count as failed.
|
|
84
|
+
- Consumers in another service: `OutboxModule.forRoot({ relay: { enabled: false } })` + an outbox store for the inbox, then in the `@EventPattern` handler `inbox.processInTransaction(tx, 'analytics', envelope.id, work)` with `OutboxEnvelope<T>` payloads.
|
|
85
|
+
|
|
86
|
+
## Operations
|
|
87
|
+
|
|
88
|
+
- Dead letters: `OutboxDeadLetters.list({ topic, key, limit })`, `get(id)`, `requeue(target)`, `purge(target)` — protect any admin routes (full payloads).
|
|
89
|
+
- Health: `OutboxRelay.stats()` (`pending`, `lagMs`, `deadLetters`, …); alert on `dead-lettered` events (`nestjs:outbox:dead-lettered`) and lag.
|
|
90
|
+
- Several instances: relays coordinate with leases; turn the relay off in API-only pods via `relay.enabled`.
|
|
91
|
+
- Prune inboxes on a schedule: `inbox.prune('30d')` (nestjs-scheduling). Version payloads. `app.enableShutdownHooks()` to drain on deploys. PostgreSQL default isolation must stay READ COMMITTED.
|
|
92
|
+
|
|
93
|
+
## Testing
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
process.env.OUTBOX_RELAY = 'off';
|
|
97
|
+
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
|
|
98
|
+
.overrideProvider(getDrizzleToken()).useValue(drizzle({ client: new PGlite() })) // after migrate()
|
|
99
|
+
.compile();
|
|
100
|
+
await moduleRef.init();
|
|
101
|
+
await service.placeOrder(dto);
|
|
102
|
+
await moduleRef.get(OutboxRelay).runOnce(); // publishes committed messages → handlers run
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Assert that a rolled-back transaction publishes nothing. Store authors: `outboxStoreContract()` / `outboxInboxStoreContract()` from `@nestjs/outbox/testing` with `{ concurrent: true }`.
|
|
106
|
+
|
|
107
|
+
## Workflow
|
|
108
|
+
|
|
109
|
+
- [ ] 1. Install; register `OutboxModule` + database store; migrations in the release pipeline.
|
|
110
|
+
- [ ] 2. Replace emit-after-save with `outbox.add(tx, …)` + `notify()`.
|
|
111
|
+
- [ ] 3. Handlers with stable consumer names; `processInTransaction` for same-DB writes; `NonRetryableMessageError` for permanent failures.
|
|
112
|
+
- [ ] 4. Routes/transports for other services; retry policy sized to downstream outages; dead-letter tooling and alerts; inbox pruning.
|
|
113
|
+
- [ ] 5. PGlite tests with `runOnce()`. Build, lint, run tests, start the app.
|
|
114
|
+
|
|
115
|
+
## Reference files
|
|
116
|
+
|
|
117
|
+
- `references/outbox-reference.md`: module/store/message options, executors, CLI, services, events, errors, delivery guarantees and store contract. Read when tuning or writing a custom store.
|
|
118
|
+
|
|
119
|
+
Sources: [Outbox](https://docs.nestjs.com/reliability/outbox)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# @nestjs/outbox reference
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
- Module options
|
|
5
|
+
- Stores, executors, migrations
|
|
6
|
+
- Messages, handlers, envelope
|
|
7
|
+
- Services
|
|
8
|
+
- Events and errors
|
|
9
|
+
- Delivery guarantees
|
|
10
|
+
- Store contract
|
|
11
|
+
|
|
12
|
+
## Module options
|
|
13
|
+
|
|
14
|
+
`forRootAsync()`: `transports` classes, `imports`, `isGlobal` at the top level; the rest from the factory/`OutboxOptionsFactory`. Token `OUTBOX_MODULE_OPTIONS`.
|
|
15
|
+
|
|
16
|
+
| Option | Default |
|
|
17
|
+
| --- | --- |
|
|
18
|
+
| `transports` | none (`local` built in, reserved) |
|
|
19
|
+
| `route` | the only destination; required with handlers + transports |
|
|
20
|
+
| `relay.enabled` / `pollInterval` / `batchSize` / `lease` / `concurrency` / `publishTimeout` | `true` / `'1s'` / 100 / `'30s'` / 10 / lease ÷ 3 |
|
|
21
|
+
| `retry.attempts` | 20 (number shorthand; `false` = one attempt) |
|
|
22
|
+
| `retry.backoff` | `'1s'` doubling to `'5m'`, equal jitter; or `(attempt, error, message) => duration` |
|
|
23
|
+
| `retry.retryIf` | every error; `false` → dead-letter now |
|
|
24
|
+
| `allowInMemoryStorage` | `false` |
|
|
25
|
+
| `isGlobal` | `true` |
|
|
26
|
+
|
|
27
|
+
## Stores, executors, migrations
|
|
28
|
+
|
|
29
|
+
`new PostgresOutboxStore({ executor, schema = 'nest_outbox', migrate }, outboxStorage)` / `MySqlOutboxStore` (MySQL 8.4 LTS or 9.x, strict sql_mode; not MariaDB). Without `outboxStorage` the store registers nowhere (scripts/tests).
|
|
30
|
+
|
|
31
|
+
| Executor | Transaction object |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| `fromDrizzle(db)` | `tx` from `db.transaction()` |
|
|
34
|
+
| `fromTypeOrm(dataSource)` | `EntityManager` from `dataSource.transaction()` or started `QueryRunner` |
|
|
35
|
+
| `fromPrisma(prisma, { maxWait = '10s', timeout = '1m' })` | tx client from `prisma.$transaction()` |
|
|
36
|
+
| `fromKysely(db)` | tx from `db.transaction().execute()` |
|
|
37
|
+
| `fromPg(pool)` | client after `BEGIN` |
|
|
38
|
+
| `fromMysql2(pool)` | connection after `beginTransaction()` |
|
|
39
|
+
|
|
40
|
+
`store.migrate()`, `PostgresOutboxStore.migrationSql({ schema, from, to, statementBreakpoints })`, `MySqlOutboxStore.migrationStatements()`. CLI `npx @nestjs/outbox migrate | status | sql [--dialect mysql] [--statement-breakpoints]` with `--url`, `--schema`. TypeORM: run `migrationSql()` in a migration; drizzle-kit: `generate --custom` and paste `sql --statement-breakpoints`.
|
|
41
|
+
|
|
42
|
+
## Messages, handlers, envelope
|
|
43
|
+
|
|
44
|
+
- `outbox.add(tx, message | message[])`: `topic`, `payload`, `key?`, `headers?`, `id?`, `delay?` | `availableAt?`.
|
|
45
|
+
- `@OnOutboxMessage(topic, { consumer, inbox = true })` on singleton providers. Context: `message`, `consumer`, `attempt`, `signal`, `processInTransaction(tx, work)` → `{ duplicate, result? }`.
|
|
46
|
+
- `ClientProxyTransport(token, { toPacket?(message, envelope) })` emits the topic with `OutboxEnvelope` `{ id, topic, key, headers, createdAt, payload }`. Consumers process one key's events sequentially if order matters (handlers are async).
|
|
47
|
+
|
|
48
|
+
## Services
|
|
49
|
+
|
|
50
|
+
| Service | Methods |
|
|
51
|
+
| --- | --- |
|
|
52
|
+
| `Outbox` | `add(tx, messages)`, `notify()` |
|
|
53
|
+
| `OutboxRelay` | `stats()` (`pending`, `ready`, `leased`, `deadLetters`, `oldestDueAt`, `lagMs`, `inFlight`), `runOnce()` (`claimed`, `published`, `retried`, `deadLettered`, `released`, `leaseLost`), `notify()`, `start()`, `stop()` |
|
|
54
|
+
| `OutboxDeadLetters` | `list({ topic, key, limit, offset })`, `get(id)`, `requeue(target)`, `purge(target)`; target = id, ids, or `{ ids, topic, key, failedBefore, all: true }` |
|
|
55
|
+
| `OutboxInbox` | `process(consumer, id, work)`, `processInTransaction(tx, consumer, id, work)`, `prune(olderThan)` |
|
|
56
|
+
|
|
57
|
+
## Events and errors
|
|
58
|
+
|
|
59
|
+
`OutboxEvents.events$` + `nestjs:outbox:<type>`: `published` (`transport`, `durationMs`), `retry-scheduled` (`error`, `attempt`, `delayMs`), `dead-lettered` (`reason`: `exhausted` | `rejected`), `lease-lost`. Catch errors in subscribers (rethrown as uncaught).
|
|
60
|
+
|
|
61
|
+
Errors (`OutboxError` base, no HTTP status): `OutboxTransactionRequiredError`, `OutboxPublishTimeoutError` (`timeoutMs`), `OutboxNoHandlerError` (`topic`; retried), `OutboxSchemaError`; and `NonRetryableMessageError` (yours to throw).
|
|
62
|
+
|
|
63
|
+
## Delivery guarantees
|
|
64
|
+
|
|
65
|
+
- Rollback → never existed. Commit → published eventually or dead-lettered with history.
|
|
66
|
+
- Relay crash after claim → another relay after lease; after publish before record → published twice (inbox dedupes).
|
|
67
|
+
- Keyed messages publish in commit order; a retrying message holds back its key; a dead-lettered one unblocks it (later messages overtake).
|
|
68
|
+
- TCP/Redis/core NATS: "published" means it left the process; consumer crashes lose it — prefer acknowledging transports for critical consumers.
|
|
69
|
+
|
|
70
|
+
## Store contract
|
|
71
|
+
|
|
72
|
+
Implement `OutboxStore` (messages + dead letters) and `OutboxInboxStore`; register with `outboxStorage.registerSource({ messages: this, inbox: this })` (consumers may register `inbox` only). Requirements: number a key's messages in commit order; `claim()` never leases to two relays nor runs ahead of an older message of its key; writes fenced by lease; two deliveries of one message can't both run work. Verify with `outboxStoreContract()` / `outboxInboxStoreContract()` (`@nestjs/outbox/testing`, `concurrent: true`) against the production engine with a pool.
|
|
73
|
+
|
|
74
|
+
BullMQ's Postgres backend can't currently join your transaction, so it is not a substitute for the outbox.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-passport-auth
|
|
3
|
+
description: Implements and maintains Passport-based authentication in NestJS 12 with @nestjs/passport and @nestjs/jwt — PassportStrategy subclasses (passport-local, passport-jwt, OAuth and other strategies), AuthGuard('local'|'jwt') and custom guard subclasses, issuing JWTs with JwtService, a global JWT guard with @Public() metadata, named and multiple strategies, request-scoped strategy dependencies via ModuleRef, PassportModule options and sessions, and GraphQL guards. Use when a project already uses @nestjs/passport or passport-* strategies, when the user explicitly asks for Passport or a specific passport strategy, or when fixing "Unknown authentication strategy", empty req.user or AuthGuard errors. Not for new projects using the first-party @nestjs/authentication (nestjs-authentication) or for permissions (nestjs-authorization).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/passport, passport, a passport-* strategy; @nestjs/jwt for tokens
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS Passport authentication
|
|
12
|
+
|
|
13
|
+
Use this skill when the project already depends on `@nestjs/passport` (or the user asks for a passport strategy). For new projects with no auth yet, suggest `@nestjs/authentication` (nestjs-authentication), which ships sessions, hashing, refresh tokens, 2FA and OIDC.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i @nestjs/passport passport passport-local @nestjs/jwt passport-jwt
|
|
17
|
+
npm i -D @types/passport-local @types/passport-jwt
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Every strategy needs `@nestjs/passport` + `passport` + the strategy package.
|
|
21
|
+
|
|
22
|
+
## How it fits together
|
|
23
|
+
|
|
24
|
+
1. A **strategy** extends `PassportStrategy(Strategy, name?)`; options go to `super()`; `validate(...)` returns the user (attached to `req.user`) or throws `UnauthorizedException`.
|
|
25
|
+
2. A **guard** `AuthGuard('local' | 'jwt' | name)` runs the strategy. Wrap it in a named class (`LocalAuthGuard`, `JwtAuthGuard`) instead of passing magic strings around.
|
|
26
|
+
3. The module imports `PassportModule` and provides the strategies (they must be providers to register with Passport).
|
|
27
|
+
|
|
28
|
+
## Recipe: login with a password, protect routes with JWT
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
// auth/local.strategy.ts
|
|
32
|
+
@Injectable()
|
|
33
|
+
export class LocalStrategy extends PassportStrategy(Strategy) {
|
|
34
|
+
constructor(private authService: AuthService) { super({ usernameField: 'email' }); }
|
|
35
|
+
async validate(email: string, password: string) {
|
|
36
|
+
const user = await this.authService.validateUser(email, password); // compare a stored hash, never plaintext
|
|
37
|
+
if (!user) throw new UnauthorizedException();
|
|
38
|
+
return user;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// auth/jwt.strategy.ts — import { ExtractJwt, Strategy as JwtPassportStrategy } from 'passport-jwt';
|
|
43
|
+
@Injectable()
|
|
44
|
+
export class JwtStrategy extends PassportStrategy(JwtPassportStrategy) {
|
|
45
|
+
constructor(config: ConfigService) {
|
|
46
|
+
super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: config.getOrThrow('JWT_SECRET') });
|
|
47
|
+
}
|
|
48
|
+
validate(payload: { sub: string; username: string }) { return { userId: payload.sub, username: payload.username }; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// auth/auth.service.ts
|
|
52
|
+
login(user: User) { return { access_token: this.jwtService.sign({ sub: user.id, username: user.username }) }; }
|
|
53
|
+
|
|
54
|
+
// auth/auth.module.ts
|
|
55
|
+
@Module({
|
|
56
|
+
imports: [UsersModule, PassportModule, JwtModule.registerAsync({
|
|
57
|
+
inject: [ConfigService],
|
|
58
|
+
useFactory: (config: ConfigService) => ({ secret: config.getOrThrow('JWT_SECRET'), signOptions: { expiresIn: '15m' } }),
|
|
59
|
+
})],
|
|
60
|
+
providers: [AuthService, LocalStrategy, JwtStrategy],
|
|
61
|
+
controllers: [AuthController],
|
|
62
|
+
})
|
|
63
|
+
export class AuthModule {}
|
|
64
|
+
|
|
65
|
+
// auth.controller.ts
|
|
66
|
+
@Public() @UseGuards(LocalAuthGuard) @Post('auth/login')
|
|
67
|
+
login(@Request() req) { return this.authService.login(req.user); }
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- Hash passwords (bcrypt or argon2; see nestjs-security-hardening). The docs' in-memory plaintext users are illustration only.
|
|
71
|
+
- Keep the JWT secret in validated config, never in a constants file.
|
|
72
|
+
- `@nestjs/jwt` `expiresIn` numbers are **seconds**; strings like `'15m'` also work.
|
|
73
|
+
|
|
74
|
+
## Global guard with public routes
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
providers: [{ provide: APP_GUARD, useClass: JwtAuthGuard }],
|
|
78
|
+
|
|
79
|
+
@Injectable()
|
|
80
|
+
export class JwtAuthGuard extends AuthGuard('jwt') {
|
|
81
|
+
constructor(private reflector: Reflector) { super(); }
|
|
82
|
+
canActivate(context: ExecutionContext) {
|
|
83
|
+
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [context.getHandler(), context.getClass()]);
|
|
84
|
+
return isPublic ? true : super.canActivate(context);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`Public = () => SetMetadata(IS_PUBLIC_KEY, true)`. Mark login, health and other open routes. With `@nestjs/authorization`, register this guard via `APP_GUARD` so it runs before the authorization guard.
|
|
90
|
+
|
|
91
|
+
## Customizing
|
|
92
|
+
|
|
93
|
+
- Override `handleRequest(err, user, info)` in the guard to change errors or allow anonymous users (return `user ?? null`).
|
|
94
|
+
- Several strategies in order: `AuthGuard(['jwt', 'api-key'])`.
|
|
95
|
+
- Name strategies: `PassportStrategy(Strategy, 'myjwt')` → `AuthGuard('myjwt')`.
|
|
96
|
+
- `PassportModule.register({ defaultStrategy: 'jwt', property: 'user', session: true })`; other options pass to `passport.authenticate()`.
|
|
97
|
+
- Sessions + logout need `express-session` with Passport session support; logout: `await new Promise((res, rej) => req.logout((e) => (e ? rej(e) : res())))`. Not applicable to JWTs.
|
|
98
|
+
- Request-scoped dependencies: strategies are global singletons; use `super({ passReqToCallback: true })` and resolve with `moduleRef.resolve(AuthService, ContextIdFactory.getByRequest(request))` in `validate(request, ...)`.
|
|
99
|
+
|
|
100
|
+
## GraphQL
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
@Injectable()
|
|
104
|
+
export class GqlAuthGuard extends AuthGuard('jwt') {
|
|
105
|
+
getRequest(context: ExecutionContext) { return GqlExecutionContext.create(context).getContext().req; }
|
|
106
|
+
}
|
|
107
|
+
export const CurrentUser = createParamDecorator((_d, ctx: ExecutionContext) => GqlExecutionContext.create(ctx).getContext().req.user);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
For a local strategy over GraphQL, copy the args into `req.body` in `getRequest()`. Configure the GraphQL `context: ({ req }) => ({ req })`.
|
|
111
|
+
|
|
112
|
+
## Gotchas
|
|
113
|
+
|
|
114
|
+
- "Unknown authentication strategy": strategy not listed in `providers`, or its module not imported, or the name differs from the guard string.
|
|
115
|
+
- `req.user` undefined in a handler: the guard isn't applied, or a global guard skipped the route as public.
|
|
116
|
+
- `passport` and the `@nestjs/passport` guards work on the Express and Node adapters ([Node adapter compatibility](https://docs.nestjs.com/http/performance)).
|
|
117
|
+
|
|
118
|
+
## Workflow
|
|
119
|
+
|
|
120
|
+
- [ ] 1. Detect existing strategies/guards; extend them rather than adding a parallel auth system.
|
|
121
|
+
- [ ] 2. Add strategy + guard class + module wiring; config-driven secrets.
|
|
122
|
+
- [ ] 3. Decide global (APP_GUARD + `@Public()`) vs per-route guards; update e2e tests to obtain a token first.
|
|
123
|
+
- [ ] 4. Build, lint, run unit and e2e tests (login → token → protected route → 401 without token), start the app.
|
|
124
|
+
|
|
125
|
+
Sources: [Passport recipe](https://docs.nestjs.com/recipes/passport) · [Guards](https://docs.nestjs.com/guards)
|