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,104 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-http-platform
|
|
3
|
+
description: Chooses and configures the NestJS 12 HTTP platform — the Node (@nestjs/platform-node), Fastify and Express adapters and their differences, adapter options (trustProxy, maxParamLength, querystringParser), body parsers and size limits, raw body for signature checks, HTTPS and multiple servers, keep-alive and forceCloseConnections, HttpAdapterHost, API versioning (URI, header, media type, custom) and response compression. Use when switching adapters, tuning HTTP performance, raising a body limit, reading the raw request body, serving HTTPS, adding v1/v2 endpoints, enabling gzip/brotli, or when the app won't exit on shutdown or req.ip shows the proxy address. Not for cookies, sessions, uploads, SSE, views or static files (nestjs-http-web-features), or for receiving webhooks (nestjs-webhooks).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/platform-express (default), @nestjs/platform-fastify or @nestjs/platform-node (12.3+)
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS HTTP platform
|
|
12
|
+
|
|
13
|
+
## Choosing an adapter
|
|
14
|
+
|
|
15
|
+
| Adapter | Package | Choose when |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `NodeAdapter` | `@nestjs/platform-node` | **Recommended from v12.3.** Fastest, runs on `node:http`, Express-style `req`/`res` helpers, so most Express middleware works unchanged |
|
|
18
|
+
| `FastifyAdapter` | `@nestjs/platform-fastify` | You need Fastify plugins, `@RouteConfig()` / `@RouteConstraints()`, or the Mercurius GraphQL driver |
|
|
19
|
+
| `ExpressAdapter` | `@nestjs/platform-express` | Used when no adapter is passed. Stay on it if you rely on Express APIs the Node adapter lacks, or on an Express-only package |
|
|
20
|
+
|
|
21
|
+
Detect the adapter from `package.json` and `main.ts` before changing anything. The adapter is a small part of each request's cost; it matters most for light routes at high request rates.
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
// main.ts — Node adapter
|
|
25
|
+
import { NestFactory } from '@nestjs/core';
|
|
26
|
+
import { NestNodeApplication, NodeAdapter } from '@nestjs/platform-node';
|
|
27
|
+
import { AppModule } from './app.module.js';
|
|
28
|
+
|
|
29
|
+
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter({ trustProxy: 'loopback' }));
|
|
30
|
+
await app.listen(process.env.PORT ?? 3000);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Always pass the application type generic (`NestNodeApplication`, `NestFastifyApplication`, `NestExpressApplication`): without it, `useBodyParser()`, `register()`, `useStaticAssets()` and `setViewEngine()` don't type-check.
|
|
34
|
+
|
|
35
|
+
## Switching adapters: checklist of differences
|
|
36
|
+
|
|
37
|
+
Node adapter vs Express (read `references/adapters.md` for the full list and Fastify specifics):
|
|
38
|
+
- Routes are matched by **specificity**, not registration order, and paths are **case-sensitive** (routes, middleware and `exclude()`).
|
|
39
|
+
- A returned string is sent as `text/plain`; no automatic `ETag` / `304`.
|
|
40
|
+
- Route params longer than 100 chars don't match (`maxParamLength`). JSON bodies with `__proto__` keys get 400 (`onProtoPoisoning`).
|
|
41
|
+
- Not available: `res.render()` (use `@Render()`), `res.download()`, `res.format()`, `req.accepts()`, `req.fresh`, mounting an Express app, Express settings (use adapter options).
|
|
42
|
+
- Upload interceptors and `MulterModule` are imported from `@nestjs/platform-node`.
|
|
43
|
+
|
|
44
|
+
Fastify:
|
|
45
|
+
- Listens on localhost only by default: in containers call `app.listen(port, '0.0.0.0')`.
|
|
46
|
+
- Middleware receives raw `req`/`res`; filters send with `response.send()`.
|
|
47
|
+
- Plugins are registered with `await app.register(plugin, options)`.
|
|
48
|
+
|
|
49
|
+
## E2E tests must use the same adapter
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
|
|
53
|
+
// Fastify: createNestApplication<NestFastifyApplication>(new FastifyAdapter()); await app.init(); await app.getHttpAdapter().getInstance().ready();
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Without an adapter argument, the testing module creates an Express app, so tests don't run on your adapter and fail if `@nestjs/platform-express` isn't installed.
|
|
57
|
+
|
|
58
|
+
## Body parsing and raw body
|
|
59
|
+
|
|
60
|
+
- Express and Node register `json` and `urlencoded` by default; add others with `app.useBodyParser('text')` (Fastify: `'text/plain'`).
|
|
61
|
+
- Size limits: Express default 100kb → `app.useBodyParser('json', { limit: '10mb' })`; Fastify default 1 MiB → `app.useBodyParser('application/json', { bodyLimit: 10_485_760 })`.
|
|
62
|
+
- Raw body (webhook signatures): `NestFactory.create(AppModule, { rawBody: true })`, then `@Req() req: RawBodyRequest<Request>` and `req.rawBody` (a `Buffer`). Works only with the built-in body parser, so don't pass `bodyParser: false`.
|
|
63
|
+
|
|
64
|
+
## Proxies, HTTPS, shutdown
|
|
65
|
+
|
|
66
|
+
- Behind a proxy or load balancer, set `trustProxy` (Node/Fastify adapter option; Express: `app.set('trust proxy', …)`) so `req.ip`, `req.protocol` and sub-domain routing see the client. Trust only proxies in front of you.
|
|
67
|
+
- HTTPS: `NestFactory.create(AppModule, { httpsOptions: { key, cert } })`; Fastify: `new FastifyAdapter({ https: httpsOptions })`. For HTTP + HTTPS at once, see `references/adapters.md` (doesn't work with GraphQL subscriptions).
|
|
68
|
+
- App doesn't exit on shutdown (often with `--watch` + `enableShutdownHooks()`): long keep-alive connections. Set `forceCloseConnections: true` in `NestFactory.create()` (Fastify needs v12.1+).
|
|
69
|
+
- Access the underlying server with `app.getHttpAdapter()` outside the app, or inject `HttpAdapterHost` (from `@nestjs/core`). Run code when listening via `httpAdapterHost.listen$`.
|
|
70
|
+
|
|
71
|
+
## Versioning
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
app.enableVersioning({ type: VersioningType.URI, defaultVersion: '1' }); // /v1/cats
|
|
75
|
+
@Controller({ path: 'cats', version: '2' }) export class CatsV2Controller {}
|
|
76
|
+
@Version(['1', '2']) @Get() findAll() {}
|
|
77
|
+
@Controller({ version: VERSION_NEUTRAL }) export class HealthController {}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- URI versioning adds the version after the global prefix; the `v` prefix is configurable (`prefix: false` to drop it).
|
|
81
|
+
- Header (`type: VersioningType.HEADER, header: 'X-API-Version'`), media type (`MEDIA_TYPE, key: 'v='`) and custom (`CUSTOM, extractor`) types are available.
|
|
82
|
+
- With versioning on and no `defaultVersion`, unversioned routes behave as `VERSION_NEUTRAL`. Register neutral routes **after** versioned routes sharing the path.
|
|
83
|
+
- Custom extractors on Express must return a single version; highest-match selection from an array works reliably only on Fastify.
|
|
84
|
+
- With header/media/custom versioning, middleware runs for all versions of a path; use a guard or interceptor for version-specific logic.
|
|
85
|
+
|
|
86
|
+
## Compression
|
|
87
|
+
|
|
88
|
+
- Express/Node: `npm i compression` → `app.use(compression())`.
|
|
89
|
+
- Fastify: `npm i @fastify/compress` → `await app.register(compression, { encodings: ['gzip', 'deflate'] })`.
|
|
90
|
+
- Under heavy load, prefer compression at the reverse proxy (Nginx) instead of in Node.
|
|
91
|
+
|
|
92
|
+
## Workflow
|
|
93
|
+
|
|
94
|
+
- [ ] 1. Detect the current adapter and app type; keep it unless the user asked to switch.
|
|
95
|
+
- [ ] 2. When switching, update `main.ts`, the e2e `createNestApplication(...)`, platform-specific imports (Multer, middleware types), and dependencies.
|
|
96
|
+
- [ ] 3. Review routes for order/case-sensitivity changes; enable `routeConflictPolicy` (nestjs-request-pipeline).
|
|
97
|
+
- [ ] 4. Add versioning/compression/body limits in `main.ts`; mirror the setup in e2e tests.
|
|
98
|
+
- [ ] 5. Build, lint, run unit and e2e tests, start the app and hit one route.
|
|
99
|
+
|
|
100
|
+
## Reference files
|
|
101
|
+
|
|
102
|
+
- `references/adapters.md`: Node adapter compatibility list and options, Fastify options/middleware/route config, multiple simultaneous servers with shutdown handling, versioning extractor example. Read when switching adapters or running HTTP and HTTPS together.
|
|
103
|
+
|
|
104
|
+
Sources: [HTTP adapters and performance](https://docs.nestjs.com/http/performance) · [HTTP adapter](https://docs.nestjs.com/faq/http-adapter) · [Keep-alive](https://docs.nestjs.com/faq/keep-alive-connections) · [Raw body](https://docs.nestjs.com/faq/raw-body) · [HTTPS & multiple servers](https://docs.nestjs.com/faq/multiple-servers) · [Versioning](https://docs.nestjs.com/http/versioning) · [Compression](https://docs.nestjs.com/http/compression)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Adapter details
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
- Node adapter: compatibility and options
|
|
5
|
+
- Fastify adapter
|
|
6
|
+
- Express adapter
|
|
7
|
+
- Multiple simultaneous servers
|
|
8
|
+
- Custom versioning extractor
|
|
9
|
+
|
|
10
|
+
## Node adapter: compatibility and options
|
|
11
|
+
|
|
12
|
+
Requests and responses are `NodeRequest` / `NodeResponse` (from `@nestjs/platform-node`), extending `IncomingMessage` / `ServerResponse` with Express-style helpers: `req.get()`, `req.is()`, `req.ip`, `req.ips`, `req.hostname`, `res.status()`, `res.send()`, `res.json()` and friends.
|
|
13
|
+
|
|
14
|
+
Express middleware that works unchanged: `helmet`, `compression`, `cookie-parser`, `express-session`, `express-rate-limit`, `csrf-csrf`, `morgan`, `passport` (and the `@nestjs/passport` guards). Where a docs chapter shows separate Express and Fastify instructions, follow the Express ones.
|
|
15
|
+
|
|
16
|
+
Deliberate differences from Express:
|
|
17
|
+
- Routes matched by specificity (like Fastify), not registration order.
|
|
18
|
+
- Case-sensitive paths for routes, middleware and `exclude()`.
|
|
19
|
+
- Returned strings are `text/plain`, not `text/html`.
|
|
20
|
+
- `req.path` is the decoded path the router matched.
|
|
21
|
+
- `res.set()` / `res.type()` don't append `; charset=utf-8`.
|
|
22
|
+
- No automatic `ETag`; conditional requests get the full response even if the handler sets `ETag`/`Last-Modified`. `res.sendFile()` and `useStaticAssets()` still answer 304.
|
|
23
|
+
- Route params over 100 chars don't match: falls through to another route, else `414`.
|
|
24
|
+
- JSON bodies with `__proto__` / `constructor.prototype` keys → 400.
|
|
25
|
+
|
|
26
|
+
Not available: `res.render()` (use `@Render()`), `res.download()`, `res.format()`, `req.accepts*()`, `req.fresh`/`req.stale`, `req.route`, mounting an Express app with `app.use()`, Express settings.
|
|
27
|
+
|
|
28
|
+
Options:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
new NodeAdapter({
|
|
32
|
+
maxParamLength: 500, // default 100
|
|
33
|
+
trustProxy: 'loopback', // true, addresses/CIDRs, or a function; a number trusts no proxy
|
|
34
|
+
querystringParser: (str) => qs.parse(str), // nested ?filter[where][name]=x; default is flat keys
|
|
35
|
+
});
|
|
36
|
+
app.useBodyParser('json', { onProtoPoisoning: 'remove' }); // or 'ignore'; also onConstructorPoisoning
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Built-in `json`, `urlencoded`, `text`, `raw` parsers take `body-parser` options (`limit`, `inflate`, `strict`, `type`). `useStaticAssets()` uses `serve-static` options plus `prefix`. `setViewEngine()` takes an engine name or `@fastify/view` options.
|
|
40
|
+
|
|
41
|
+
Other packages: `@nestjs/serve-static` v12.1.1+ works without `express` (SPA fallback needs `@nestjs/platform-node` v12.3.1+). GraphQL: `@nestjs/apollo` v14.1.1+; Mercurius requires Fastify.
|
|
42
|
+
|
|
43
|
+
## Fastify adapter
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
|
|
47
|
+
|
|
48
|
+
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter({ logger: true }));
|
|
49
|
+
await app.listen(3000, '0.0.0.0'); // Fastify listens on localhost only by default
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- Redirect inside a handler: `res.status(302).redirect('/login')`.
|
|
53
|
+
- Middleware gets raw objects: `use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void)` (via `@fastify/middie`).
|
|
54
|
+
- `@RouteConfig({ output: 'x' })` → `req.routeConfig.output`; `@RouteConstraints({ version: '1.2.x' })`. Both from `@nestjs/platform-fastify`.
|
|
55
|
+
- Plugins: `await app.register(plugin, opts)` (requires the `NestFastifyApplication` type).
|
|
56
|
+
|
|
57
|
+
## Express adapter
|
|
58
|
+
|
|
59
|
+
Default when no adapter is passed. To stay on Express once the Node adapter becomes the default (v13), pass `new ExpressAdapter()` explicitly with `NestExpressApplication`.
|
|
60
|
+
|
|
61
|
+
## Multiple simultaneous servers
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
const server = express();
|
|
65
|
+
const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
|
|
66
|
+
await app.init();
|
|
67
|
+
const httpServer = http.createServer(server).listen(3000);
|
|
68
|
+
const httpsServer = https.createServer(httpsOptions, server).listen(443);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Nest doesn't close servers you created. Close them in a provider implementing `OnApplicationShutdown` that collects servers (`addHttpServer(server)`) and awaits `server.close()` for each; register them with `app.get(ShutdownObserver).addHttpServer(httpServer)`. Doesn't work with GraphQL subscriptions.
|
|
72
|
+
|
|
73
|
+
## Custom versioning extractor
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
const extractor = (request: FastifyRequest): string | string[] =>
|
|
77
|
+
[request.headers['custom-versioning-field'] ?? '']
|
|
78
|
+
.flatMap((v) => v.split(','))
|
|
79
|
+
.filter((v) => !!v)
|
|
80
|
+
.sort()
|
|
81
|
+
.reverse();
|
|
82
|
+
|
|
83
|
+
app.enableVersioning({ type: VersioningType.CUSTOM, extractor });
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Versions are matched highest first. On Express, return one version only.
|
|
87
|
+
|
|
88
|
+
Middleware for one version (URI versioning): `consumer.apply(M).forRoutes({ path: 'cats', method: RequestMethod.GET, version: '2' })`.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-http-web-features
|
|
3
|
+
description: Implements browser-facing HTTP features in NestJS 12 — built-in cookies (@Cookies, @SignedCookies, httpAdapter.setCookie/clearCookie, cookie signing with secret rotation), sessions (express-session, @fastify/secure-session), file uploads with Multer or @fastify/multipart (FileInterceptor, ParseFilePipe, size limits, disk vs memory storage, streaming uploads), file downloads with StreamableFile, Server-Sent Events (@Sse, @SseSignal, client disconnect cleanup), MVC template rendering (@Render, hbs, @fastify/view) and serving static files or an SPA (@nestjs/serve-static). Use when reading or setting cookies, storing session data, accepting or validating uploads, returning files, pushing live updates over SSE, rendering server-side views, or hosting a frontend build. Not for adapter choice, body limits or raw body (nestjs-http-platform), cloud object storage (nestjs-file-storage) or WebSockets (nestjs-websockets).
|
|
4
|
+
compatibility: NestJS 12.x; Express, Fastify (uploads 12.1+) or Node adapter
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS HTTP web features
|
|
12
|
+
|
|
13
|
+
Detect the adapter first: several features import from the platform package (`@nestjs/platform-express`, `@nestjs/platform-fastify`, `@nestjs/platform-node`).
|
|
14
|
+
|
|
15
|
+
## Cookies (built in, no cookie-parser needed)
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
// main.ts — only needed for signed cookies; validate COOKIE_SECRET at startup
|
|
19
|
+
const app = await NestFactory.create(AppModule, { cookies: { secret: [process.env.COOKIE_SECRET!, process.env.COOKIE_SECRET_OLD!] } });
|
|
20
|
+
|
|
21
|
+
@Controller('session')
|
|
22
|
+
export class SessionController {
|
|
23
|
+
constructor(private readonly adapterHost: HttpAdapterHost) {}
|
|
24
|
+
|
|
25
|
+
@Post('login')
|
|
26
|
+
login(@Res({ passthrough: true }) res: unknown) {
|
|
27
|
+
this.adapterHost.httpAdapter.setCookie(res, 'uid', '42', { signed: true, httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 24 });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
@Get('me')
|
|
31
|
+
me(@SignedCookies('uid') uid?: string) { // undefined if missing, unsigned or tampered
|
|
32
|
+
if (!uid) throw new UnauthorizedException();
|
|
33
|
+
return { uid };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
@Delete('logout')
|
|
37
|
+
logout(@Res({ passthrough: true }) res: unknown) { this.adapterHost.httpAdapter.clearCookie(res, 'uid'); }
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `@Cookies('name', ParseIntPipe)` reads unsigned values; missing → 400 unless the pipe is `optional`. A global `ValidationPipe` skips cookie params unless `validateCustomDecorators: true`.
|
|
42
|
+
- **`maxAge` is in seconds** (RFC 6265), unlike Express `res.cookie()` (milliseconds).
|
|
43
|
+
- Never trust `@Cookies()` for identity; use `@SignedCookies()`. Signing gives integrity, not confidentiality, and the cookie name isn't signed.
|
|
44
|
+
- An `undefined` secret counts as no secret: signed operations throw at request time (500). An empty secret throws at app creation.
|
|
45
|
+
- `__Host-` / `__Secure-` prefixes aren't enforced: set `secure: true` (+ `path: '/'`, no `domain` for `__Host-`) yourself.
|
|
46
|
+
- Existing `cookie-parser` / `@fastify/cookie` setups keep working alongside the decorators.
|
|
47
|
+
|
|
48
|
+
## Sessions
|
|
49
|
+
|
|
50
|
+
- Express/Node: `npm i express-session` → `app.use(session({ secret, resave: false, saveUninitialized: false }))`; read with `@Session() session`.
|
|
51
|
+
- The default memory store leaks and doesn't scale past one process: use a production store.
|
|
52
|
+
- `cookie.secure: true` needs HTTPS; behind a proxy, configure trust proxy.
|
|
53
|
+
- Fastify: `npm i @fastify/secure-session` → `await app.register(secureSession, { secret, salt })`; use `session.get()` / `session.set()`.
|
|
54
|
+
|
|
55
|
+
## File uploads
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
@Post('avatar')
|
|
59
|
+
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 5 * 1024 * 1024 } })) // stop oversized uploads early
|
|
60
|
+
upload(
|
|
61
|
+
@UploadedFile(new ParseFilePipeBuilder()
|
|
62
|
+
.addFileTypeValidator({ fileType: /^image\/(jpeg|png)$/ })
|
|
63
|
+
.addMaxSizeValidator({ maxSize: 5 * 1024 * 1024 })
|
|
64
|
+
.build({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY }))
|
|
65
|
+
file: Express.Multer.File,
|
|
66
|
+
) { return { size: file.size }; }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- Import interceptors from the adapter's package: `@nestjs/platform-express` (+ `npm i -D @types/multer`), `@nestjs/platform-node`, or `@nestjs/platform-fastify/multipart` (12.1+, `npm i @fastify/multipart`, auto-registered; files typed `UploadedMultipartFile`). Fastify interceptors fail to start on Express.
|
|
70
|
+
- Multer keeps files in memory and has **no default size limit**: always set `limits.fileSize`. Validators run after the whole file is received; `limits` stops early. Fastify defaults to 1 MiB per file (413 above it).
|
|
71
|
+
- Large files: `diskStorage()` from `multer`, or `FileStreamInterceptor()` on Fastify to stream.
|
|
72
|
+
- Variants: `FilesInterceptor('files', 5)` + `@UploadedFiles()`, `FileFieldsInterceptor([...])`, `AnyFilesInterceptor()`, `NoFilesInterceptor()`.
|
|
73
|
+
- Defaults: `MulterModule.register({ dest })` / `registerAsync()`; Fastify: `MultipartModule.register()`.
|
|
74
|
+
- Files are required by default: `build({ fileIsRequired: false })`.
|
|
75
|
+
- Multer only handles `multipart/form-data`.
|
|
76
|
+
|
|
77
|
+
Read `references/uploads-streaming.md` for custom `FileValidator`s, Fastify setup and streaming uploads.
|
|
78
|
+
|
|
79
|
+
## Downloads
|
|
80
|
+
|
|
81
|
+
Return `new StreamableFile(createReadStream(path), { type: 'application/pdf', disposition: 'attachment; filename="report.pdf"' })`. It keeps interceptors working (unlike piping into `@Res()`). Handle stream errors with `.setErrorHandler()` (Express/Node; on Fastify errors go to exception filters).
|
|
82
|
+
|
|
83
|
+
## Server-Sent Events
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
@Sse('events')
|
|
87
|
+
async events(@SseSignal() signal: AbortSignal): Promise<Observable<MessageEvent>> {
|
|
88
|
+
return interval(1000).pipe(map((n) => ({ data: { n } })), finalize(() => this.logger.log('client gone')));
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
- Must return an `Observable` (or a Promise of one). Nest unsubscribes on client disconnect; release resources in `finalize`.
|
|
93
|
+
- For async setup, check `signal.aborted` before returning; make abort cleanup idempotent.
|
|
94
|
+
- Status/headers: `@Header()`, or set them on `@Res({ passthrough: true })` before the stream starts (12.1.3+).
|
|
95
|
+
|
|
96
|
+
## MVC and static files
|
|
97
|
+
|
|
98
|
+
- Views: `app.useStaticAssets(join(import.meta.dirname, '..', 'public'))`, `app.setBaseViewsDir(...)`, `app.setViewEngine('hbs')`, then `@Render('index')` returning locals. Node adapter supports `@Render()` but not `res.render()`. Fastify: `@fastify/view` + `@fastify/static`, `@Render('index.hbs')`.
|
|
99
|
+
- SPA: `npm i @nestjs/serve-static` → `ServeStaticModule.forRoot({ rootPath: join(import.meta.dirname, '..', 'client') })`. By default every unmatched path returns `index.html`; tune with `serveRoot`, `renderPath`, `exclude`. On Fastify set `serveStaticOptions.fallthrough: true`.
|
|
100
|
+
|
|
101
|
+
## Workflow
|
|
102
|
+
|
|
103
|
+
- [ ] 1. Detect the adapter and import platform-specific pieces from its package.
|
|
104
|
+
- [ ] 2. Configure secrets (cookie, session) through validated config (nestjs-configuration).
|
|
105
|
+
- [ ] 3. Set upload size limits in the interceptor and validators on the parameter.
|
|
106
|
+
- [ ] 4. Add e2e tests: cookies via `Set-Cookie` headers, uploads via supertest `.attach()`, SSE via a streamed request.
|
|
107
|
+
- [ ] 5. Build, lint, run unit and e2e tests, start the app.
|
|
108
|
+
|
|
109
|
+
## Reference files
|
|
110
|
+
|
|
111
|
+
- `references/uploads-streaming.md`: custom `FileValidator`, async Multer config, disk storage naming, Fastify multipart setup and `FileStreamInterceptor`, `StreamableFile` headers and error handling, cookie invalid-input rules. Read when building upload or download endpoints beyond the basic example.
|
|
112
|
+
|
|
113
|
+
Sources: [Cookies](https://docs.nestjs.com/http/cookies) · [Session](https://docs.nestjs.com/http/session) · [File upload](https://docs.nestjs.com/http/file-upload) · [Server-Sent Events](https://docs.nestjs.com/http/server-sent-events) · [MVC](https://docs.nestjs.com/http/mvc) · [Serve static](https://docs.nestjs.com/recipes/serve-static)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Uploads, streaming and cookie details
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
- Validators
|
|
5
|
+
- Multer configuration (Express / Node adapter)
|
|
6
|
+
- Fastify multipart (12.1+)
|
|
7
|
+
- Streaming uploads (Fastify only)
|
|
8
|
+
- Downloads with StreamableFile
|
|
9
|
+
- Cookie options and rejected input
|
|
10
|
+
|
|
11
|
+
## Validators
|
|
12
|
+
|
|
13
|
+
`ParseFilePipe({ validators: [...], errorHttpStatusCode, fileIsRequired })` or `ParseFilePipeBuilder().addFileTypeValidator().addMaxSizeValidator().build({...})`.
|
|
14
|
+
|
|
15
|
+
Built-in:
|
|
16
|
+
- `MaxFileSizeValidator({ maxSize })`: bytes, size must be less than the value.
|
|
17
|
+
- `FileTypeValidator({ fileType })`: string or RegExp; checks the **magic number** of the content by default (`skipMagicNumbersValidation: true` to trust the client MIME type).
|
|
18
|
+
|
|
19
|
+
Custom validator:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
export class ImageDimensionsValidator extends FileValidator<{ maxWidth: number }> {
|
|
23
|
+
async isValid(file?: Express.Multer.File) { /* inspect file.buffer */ return true; }
|
|
24
|
+
buildErrorMessage() { return `Image wider than ${this.validationOptions.maxWidth}px`; }
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
For arrays, pass the pipe to `@UploadedFiles()`; validators run on each file.
|
|
29
|
+
|
|
30
|
+
## Multer configuration (Express / Node adapter)
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
MulterModule.registerAsync({
|
|
34
|
+
imports: [ConfigModule],
|
|
35
|
+
useFactory: (config: ConfigService) => ({ dest: config.get<string>('UPLOAD_DIR'), limits: { fileSize: 10 * 1024 * 1024 } }),
|
|
36
|
+
inject: [ConfigService],
|
|
37
|
+
});
|
|
38
|
+
// or useClass: MulterConfigService implements MulterOptionsFactory { createMulterOptions(): MulterModuleOptions }
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Disk storage with safe names:
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
import { diskStorage } from 'multer';
|
|
45
|
+
FileInterceptor('file', {
|
|
46
|
+
storage: diskStorage({
|
|
47
|
+
destination: './uploads',
|
|
48
|
+
filename: (_req, file, cb) => cb(null, `${randomUUID()}${extname(file.originalname)}`),
|
|
49
|
+
}),
|
|
50
|
+
limits: { fileSize: 50 * 1024 * 1024 },
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
A `destination` function (instead of a string) means you must create the directory. `FileInterceptor()` may not work on some cloud platforms such as Firebase.
|
|
55
|
+
|
|
56
|
+
## Fastify multipart (12.1+)
|
|
57
|
+
|
|
58
|
+
- `npm i @fastify/multipart`. The adapter registers the plugin automatically when an upload interceptor is used.
|
|
59
|
+
- Import from `@nestjs/platform-fastify/multipart` (also re-exported from the package root). Types: `UploadedMultipartFile`, `MultipartOptions`, `MultipartModule`, `MultipartOptionsFactory.createMultipartOptions()`; `memoryStorage()` / `diskStorage()` from the same path.
|
|
60
|
+
- Stricter defaults than Multer: `fileSize` = Fastify `bodyLimit` (1 MiB), max 1000 parts; oversize → `413`.
|
|
61
|
+
- Raise limits per route (`limits`), per module (`MultipartModule.register()`), or app-wide: `new FastifyAdapter({ multipart: { limits: { fileSize: 10 * 1024 * 1024 } } })`. Route limits merge over module over app (except `fieldNameSize`).
|
|
62
|
+
- `multipart: true` (or options) is required when an interceptor is created outside DI (`app.useGlobalInterceptors(new (FileInterceptor('f'))())`) or only used in lazy-loaded modules.
|
|
63
|
+
- Register the plugin yourself with `app.register(multipart, opts)`, not on the raw Fastify instance after `init()` (`FST_ERR_DEC_ALREADY_PRESENT`).
|
|
64
|
+
- Differs from Multer: rejects prototype-polluting field names; JSON text parts arrive parsed; `attachFieldsToBody` unsupported.
|
|
65
|
+
|
|
66
|
+
## Streaming uploads (Fastify only)
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { FileStreamInterceptor, MultipartFileStream } from '@nestjs/platform-fastify/multipart';
|
|
70
|
+
|
|
71
|
+
@Post('upload')
|
|
72
|
+
@UseInterceptors(FileStreamInterceptor('file', { limits: { fileSize: 1024 * 1024 * 1024 } }))
|
|
73
|
+
async upload(@UploadedFile() file: MultipartFileStream, @Body() body) {
|
|
74
|
+
const path = join('uploads', randomUUID());
|
|
75
|
+
await pipeline(file.stream, createWriteStream(path));
|
|
76
|
+
return { path };
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Rules: text fields must come **before** the file; one file only; `MaxFileSizeValidator` and magic-number checks don't apply (the `fileSize` limit still does, raising `PayloadTooLargeException`); unread data is discarded before responding.
|
|
81
|
+
|
|
82
|
+
## Downloads with StreamableFile
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
@Get('report')
|
|
86
|
+
report(): StreamableFile {
|
|
87
|
+
return new StreamableFile(createReadStream(join(process.cwd(), 'report.pdf')), {
|
|
88
|
+
type: 'application/pdf',
|
|
89
|
+
disposition: 'attachment; filename="report.pdf"',
|
|
90
|
+
}).setErrorHandler((err, res) => {
|
|
91
|
+
if (res.headersSent) { res.end(); return; }
|
|
92
|
+
res.statusCode = 400;
|
|
93
|
+
res.end(err.message);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Headers can also come from `@Header()` or `@Res({ passthrough: true })`. The error handler applies on Express and Node; on Fastify, stream errors go to exception filters (500 by default). Not for GraphQL or microservices.
|
|
99
|
+
|
|
100
|
+
## Cookie options and rejected input
|
|
101
|
+
|
|
102
|
+
Options: `maxAge` (seconds), `expires`, `domain`, `path` (default `/`), `secure`, `httpOnly`, `sameSite` (`'strict' | 'lax' | 'none'`), `priority`, `partitioned`, `signed`. Only `path` has a default; set `httpOnly`, `secure`, `sameSite` explicitly for credentials.
|
|
103
|
+
|
|
104
|
+
`setCookie()` / `clearCookie()` throw `TypeError` instead of escaping when the name or attributes are invalid (e.g. contain `;`, CR, LF), when `sameSite`/`priority` has an unknown value, or when `sameSite: 'none'` or `partitioned: true` is used without `secure: true`.
|
|
105
|
+
|
|
106
|
+
`clearCookie()` must receive the same `path`/`domain` as when the cookie was set.
|
|
107
|
+
|
|
108
|
+
Secret rotation: `cookies: { secret: ['current', 'previous'] }` signs with the first and verifies with all.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-i18n
|
|
3
|
+
description: Internationalizes NestJS 12 responses with the first-party @nestjs/i18n package — JSON catalogs per locale and namespace, typed keys via I18nTypes, I18nModule.forRoot/forRootAsync with ordered locale resolvers (query, header, Accept-Language, cookie, custom afterGuards resolvers from the user profile), region fallbacks, Content-Language/Vary headers, I18nService.t with placeholders and CLDR plural forms, the t() helper for exceptions and pipes, I18nValidationPipe and I18nStandardSchemaValidationPipe for translated class-validator/Zod messages, Intl number and date formatting, GraphQL fields, microservices and WebSockets, missingKey policies, hot-reloading catalogs, ICU formatters, I18nContext.run for jobs, and catalog tests. Use when the API must answer in the user's language, translate errors or validation messages, format prices/dates per locale, or test translations. Not for the content of emails by itself (nestjs-mail templates take a locale) or general validation (nestjs-validation-serialization).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/i18n; resolveJsonModule for typed keys; optional intl-messageformat for ICU
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS i18n (@nestjs/i18n)
|
|
12
|
+
|
|
13
|
+
The first-party `@nestjs/i18n` resolves the locale once per request into AsyncLocalStorage, so singleton services translate without the request. If the project uses the community `nestjs-i18n` package, keep its APIs unless asked to migrate.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i @nestjs/i18n
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Catalogs, module, types
|
|
20
|
+
|
|
21
|
+
```text
|
|
22
|
+
src/i18n/en/orders.json src/i18n/pl/orders.json src/i18n/en/validation.json src/i18n/translations.ts
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
// src/i18n/en/orders.json — file name = namespace; key orders.notFound
|
|
27
|
+
{ "items": { "one": "{count} item", "other": "{count} items" }, "confirmed": "Order #{id} is confirmed: {items}.", "notFound": "Order #{id} was not found." }
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
I18nModule.forRootAsync({
|
|
32
|
+
inject: [ConfigService],
|
|
33
|
+
useFactory: (config: ConfigService) => ({
|
|
34
|
+
defaultLocale: 'en',
|
|
35
|
+
supportedLocales: ['en', 'pl', 'de'], // pin: stray directories never become locales
|
|
36
|
+
fallbacks: { 'de-AT': 'de' }, // region keeps its own formatting, messages from de
|
|
37
|
+
loader: new JsonI18nLoader({ path: join(import.meta.dirname, 'i18n'), watch: config.get('NODE_ENV') === 'development' }),
|
|
38
|
+
missingKey: config.get('NODE_ENV') === 'production' ? 'fallback' : 'throw',
|
|
39
|
+
}),
|
|
40
|
+
resolvers: [new QueryLocaleResolver('lang'), new HeaderLocaleResolver('x-lang'), CustomerLocaleResolver, new AcceptLanguageLocaleResolver()],
|
|
41
|
+
imports: [CustomersModule], // classes and imports stay at the top level
|
|
42
|
+
}),
|
|
43
|
+
|
|
44
|
+
// src/i18n/translations.ts — English catalog is the source of truth
|
|
45
|
+
import type orders from './en/orders.json';
|
|
46
|
+
export interface Translations { orders: typeof orders; validation: typeof validation }
|
|
47
|
+
declare module '@nestjs/i18n' { interface I18nTypes { translations: Translations } }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
- Add `"assets": ["i18n/**/*.json"], "watchAssets": true` to `nest-cli.json`; enable `resolveJsonModule`.
|
|
51
|
+
- Resolvers run in order; first supported candidate wins; `pl-PL` → `pl` automatically; no match or no request → `defaultLocale`. Responses get `Content-Language` and `Vary`.
|
|
52
|
+
- Profile language: a `LocaleResolver` subclass with `readonly afterGuards = true` reading the authenticated user from `executionContext` (guards see the pre-guard locale).
|
|
53
|
+
|
|
54
|
+
## Translate
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
constructor(private readonly i18n: I18nService) {}
|
|
58
|
+
|
|
59
|
+
confirm(order: Order) {
|
|
60
|
+
const count = order.items.reduce((n, i) => n + i.quantity, 0);
|
|
61
|
+
const items = this.i18n.t('orders.items', { args: { count } }); // plural chosen by count via Intl.PluralRules
|
|
62
|
+
return this.i18n.t('orders.confirmed', { args: { id: order.id, items } });
|
|
63
|
+
}
|
|
64
|
+
findOne(id: number) {
|
|
65
|
+
const order = this.repo.find(id);
|
|
66
|
+
if (!order) throw new NotFoundException(this.i18n.t('orders.notFound', { args: { id } }));
|
|
67
|
+
return order;
|
|
68
|
+
}
|
|
69
|
+
summary(order: Order) {
|
|
70
|
+
return {
|
|
71
|
+
total: this.i18n.formatNumber(order.total, { style: 'currency', currency: order.currency }), // currency from data, never the locale
|
|
72
|
+
placedAt: this.i18n.formatDate(order.createdAt, { dateStyle: 'long', timeZone: 'UTC' }),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- Keys are type-checked; `translate()` takes runtime-built keys. Plural messages require a `count` arg; placeholders can't nest — compose messages.
|
|
78
|
+
- Without DI (pipes created with `new`): `t('orders.invalidId')`, e.g. `new ParseIntPipe({ exceptionFactory: () => new BadRequestException(t('orders.invalidId')) })`.
|
|
79
|
+
- `@CurrentLocale()` param, `I18nContext.locale`, `I18nContext.setLocale(l)` (returns matched locale or `undefined`).
|
|
80
|
+
- Outside requests (cron, queues, emails) the default locale applies and `t()` returns the key: wrap work in `i18nContext.run(customer.locale, () => …)`.
|
|
81
|
+
- Arguments are inserted raw: escape when the message goes into HTML.
|
|
82
|
+
|
|
83
|
+
## Validation messages
|
|
84
|
+
|
|
85
|
+
- class-validator: replace `ValidationPipe` with `{ provide: APP_PIPE, useValue: new I18nValidationPipe({ whitelist: true, transform: true }) }`. Constraints read `validation.<constraintName>` (`validation.isInt`); point one at a key with `@Max(10, { message: i18nValidationMessage('orders.tooManyItems') })`. Placeholders: `property`, `path`, `value`, `constraint1…`, `count`.
|
|
86
|
+
- Standard Schema (Zod/Valibot/ArkType): `new I18nStandardSchemaValidationPipe()`; custom keys with `i18nIssueMessage('orders.tooManyItems')`; issues resolve `validation.invalid_format.regex` → `validation.too_small.string` → `validation.too_small`.
|
|
87
|
+
- Untranslated constraints keep the library message.
|
|
88
|
+
|
|
89
|
+
## Other transports
|
|
90
|
+
|
|
91
|
+
- GraphQL: localized values via field resolvers with `I18nService`. With `setGlobalPrefix()`, set `useGlobalPrefix: true` on `GraphQLModule`, or the middleware doesn't cover it. Subscriptions aren't wrapped.
|
|
92
|
+
- Microservices/gateways: resolved in a global interceptor; add a resolver reading the locale from message data or `switchToRpc().getContext()`. For `ws`, store the upgrade request on the client in `handleConnection`.
|
|
93
|
+
|
|
94
|
+
## Testing
|
|
95
|
+
|
|
96
|
+
- E2E: send `Accept-Language`/`?lang=`/`x-lang` and assert translated bodies.
|
|
97
|
+
- Unit: `i18nContext.run('pl', () => service.describe(order))`.
|
|
98
|
+
- Swap catalogs: `.overrideProvider(I18nLoader).useValue(new InMemoryI18nLoader(catalogs))`.
|
|
99
|
+
- Catalog test in CI: same keys and placeholders as English, and every plural form `new Intl.PluralRules(lang).resolvedOptions().pluralCategories` needs.
|
|
100
|
+
|
|
101
|
+
## Production checklist
|
|
102
|
+
|
|
103
|
+
`dist/i18n` exists after build; `'fallback'` in production, `'throw'` elsewhere + catalog test; `watch` off; pinned `supportedLocales`; regions in `fallbacks`; locale set explicitly in background work; CDN honours `Vary`; GraphQL under the prefix; HTML-escape messages; currency/time zone from data.
|
|
104
|
+
|
|
105
|
+
## Workflow
|
|
106
|
+
|
|
107
|
+
- [ ] 1. Install; catalogs per locale; assets; typed `Translations`.
|
|
108
|
+
- [ ] 2. Register with resolvers in priority order and environment-based `missingKey`/`watch`.
|
|
109
|
+
- [ ] 3. Replace hard-coded strings in services/exceptions with `t()`; swap the validation pipe.
|
|
110
|
+
- [ ] 4. Format numbers/dates with `I18nService`; handle background jobs with `I18nContext.run`.
|
|
111
|
+
- [ ] 5. E2E + catalog tests. Build, lint, run tests, start the app.
|
|
112
|
+
|
|
113
|
+
Sources: [Internationalization](https://docs.nestjs.com/application/i18n)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-idempotency
|
|
3
|
+
description: Makes NestJS 12 operations safe to retry with the first-party @nestjs/idempotency package — IdempotencyModule.forRoot with per-user scope, @Idempotent({ required }) on HTTP routes, GraphQL mutations (idempotencyKey argument) and microservice event handlers (keyFrom payload), Idempotency-Key fingerprinting, 409 in-flight / 422 reused / Idempotent-Replayed replay semantics, storeIf for which outcomes are stored, ttl/lockTtl/retryAfter tuning, AES-GCM encryption of stored responses, writing an IdempotencyStore for PostgreSQL (Drizzle/TypeORM/Prisma) or Redis with registerSource and the contract test suite, client retry rules, events, and testing duplicate and concurrent requests. Use when payments, orders or other side effects must not happen twice on client retries, when deduplicating redelivered messages/events, or when implementing Idempotency-Key headers. Not for server-side retries (nestjs-resilience), outbox delivery (nestjs-outbox) or distributed locks (nestjs-locks).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/idempotency; a database or Redis for the store
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS idempotency keys (@nestjs/idempotency)
|
|
12
|
+
|
|
13
|
+
Don't hand-roll "check then insert" key tables: they race. `@nestjs/idempotency` claims keys atomically, renews locks, stores the final response and replays it.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i @nestjs/idempotency
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Register and mark handlers
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
IdempotencyModule.forRootAsync({
|
|
23
|
+
useFactory: () => ({
|
|
24
|
+
scope: (req: { user?: User }) => req.user?.id, // per-user namespace (runs after guards)
|
|
25
|
+
ttl: '48h', // > client retry window (default 24h)
|
|
26
|
+
lockTtl: '45s', // crash recovery; renewed every lockTtl/3 (default 60s)
|
|
27
|
+
retryAfter: '2s', // Retry-After on 409 (default 1s)
|
|
28
|
+
encryption: { keys: process.env.IDEMPOTENCY_KEYS!.split(',') }, // newest first; when responses hold PII/payment data
|
|
29
|
+
}),
|
|
30
|
+
}),
|
|
31
|
+
|
|
32
|
+
@Post(':id/pay')
|
|
33
|
+
@Idempotent({ required: true }) // 400 IDEMPOTENCY_KEY_REQUIRED without a key
|
|
34
|
+
pay(@Param('id') id: string, @Body() dto: PayOrderDto, @CurrentUser() user: User) {
|
|
35
|
+
return this.orders.pay(id, user, dto);
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
- Import `IdempotencyModule` **before** `ResilienceModule` and keep its interceptor outermost (the module warns otherwise).
|
|
40
|
+
- Behaviour per key (fingerprint = scope + method + URL + body):
|
|
41
|
+
|
|
42
|
+
| Situation | Response |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| First call still running | 409 `IDEMPOTENCY_KEY_IN_USE` + `Retry-After` |
|
|
45
|
+
| First call completed | stored status/body + `Idempotent-Replayed: true`; handler not run |
|
|
46
|
+
| Same key, different request | 422 `IDEMPOTENCY_KEY_REUSED` |
|
|
47
|
+
|
|
48
|
+
- Stored by default: 2xx and 4xx (replayed). Not stored: 5xx/unknown errors (key released), streams/`@Res()`. Change with `storeIf: (status, error) => status < 500 || error instanceof ChargeCapturedError`.
|
|
49
|
+
- Replayed errors come back as plain `HttpException`s (custom `instanceof` checks in filters see the base class).
|
|
50
|
+
- Per-handler overrides: `required`, `ttl`, `lockTtl`, `retryAfter`, `keyFrom`, `scope`, `fingerprint` (e.g. ignore a client timestamp), `storeIf`.
|
|
51
|
+
- Still keep the state check in the service (conditional update): two taps with two keys are two attempts. Pass downstream providers a key derived from user id + idempotency key.
|
|
52
|
+
|
|
53
|
+
## GraphQL and messages
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
@Mutation(() => PaymentReceipt)
|
|
57
|
+
@Idempotent({ required: true })
|
|
58
|
+
payOrder(@Args('orderId', { type: () => ID }) orderId: string, @Args('input') input: PayOrderDto,
|
|
59
|
+
@Args('idempotencyKey') _key: string, @CurrentUser() user: User) { … } // errors in extensions: code, httpStatus, retryAfter
|
|
60
|
+
|
|
61
|
+
@EventPattern('order.paid')
|
|
62
|
+
@Idempotent({ required: true, keyFrom: { payload: 'eventId' } }) // id derived from data: `order-paid:${orderId}`
|
|
63
|
+
async onOrderPaid(@Payload() event: OrderPaidEvent) { … }
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
- Message consumers: no `scope` needed for globally unique event ids; longer `ttl` (e.g. `'7d'`) for redeliveries from DLQs. Record keys include the handler, so several handlers for one event each run once. On 409 with ack-based brokers, don't ack — let it redeliver.
|
|
67
|
+
- Scope per context: `scope: { http: (req) => …, graphql: (req) => …, rpc: (payload) => … }`.
|
|
68
|
+
|
|
69
|
+
## Store (required in production)
|
|
70
|
+
|
|
71
|
+
In-memory records vanish on restart and aren't shared; production refuses to start without a store (unless `allowInMemoryStorage`). Implement `IdempotencyStore` in your app and register it:
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
@Injectable()
|
|
75
|
+
export class DrizzleIdempotencyStore implements IdempotencyStore {
|
|
76
|
+
constructor(@InjectDrizzle() private readonly db: Database, storage: IdempotencyStorage) { storage.registerSource(this); }
|
|
77
|
+
acquire(key, owner, fingerprint, lockTtl) { /* one INSERT … ON CONFLICT (key_hash) DO UPDATE … WHERE expires_at <= now RETURNING; else read record */ }
|
|
78
|
+
complete(key, owner, response, ttl) { /* UPDATE … WHERE key_hash = ? AND owner = ? AND expires_at > now */ }
|
|
79
|
+
release(key, owner) { /* DELETE with the same owner/expiry guard */ }
|
|
80
|
+
extend(key, owner, lockTtl) { /* UPDATE expiry with the same guard */ }
|
|
81
|
+
}
|
|
82
|
+
// table idempotency_keys: key_hash (sha256, PK), key, fingerprint, owner (null when complete), response json (not jsonb), expires_at bigint
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- All four methods must be atomic compare-and-set (owner = fencing token). Redis: one Lua script per method, no pruning needed. Prisma: `$queryRaw` for acquire, `updateMany/deleteMany` with owner+expiry in `where`.
|
|
86
|
+
- Database stores: migrations for the table, scheduled `prune()`, synced clocks. Redis shared by services: prefix per service.
|
|
87
|
+
- Verify with `idempotencyStoreContract()` from `@nestjs/idempotency/testing`, `{ concurrent: true }`, against PostgreSQL with a pool.
|
|
88
|
+
|
|
89
|
+
## Clients
|
|
90
|
+
|
|
91
|
+
Create the key when the user decides (tap Pay), persist it with the pending action, reuse it on every retry; new key only for a new decision. Retry on network errors, 409 `IDEMPOTENCY_KEY_IN_USE` (after Retry-After), 5xx, 429; never on 422 or other 4xx. Check `code`, not just status. Browsers: allow `Idempotency-Key` in CORS `allowedHeaders`, expose `Idempotent-Replayed` and `Retry-After`.
|
|
92
|
+
|
|
93
|
+
## Testing
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
.overrideProvider(DrizzleIdempotencyStore).useValue(new InMemoryIdempotencyStore())
|
|
97
|
+
// slow fake side effect (await setTimeout(100)) so concurrent duplicates overlap
|
|
98
|
+
const [a, b] = await Promise.all([pay('key-2'), pay('key-2')]);
|
|
99
|
+
expect([a.status, b.status].sort()).toEqual([201, 409]);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`app.get(IdempotencyStorage).source.peek('usr_alice:key-1')` inspects raw records.
|
|
103
|
+
|
|
104
|
+
## Workflow
|
|
105
|
+
|
|
106
|
+
- [ ] 1. Install; `forRootAsync` with `scope`, TTLs, encryption; import before resilience.
|
|
107
|
+
- [ ] 2. `@Idempotent({ required: true })` on money-moving/creating endpoints, mutations and event handlers.
|
|
108
|
+
- [ ] 3. Implement and register the store + migration; run the contract suite.
|
|
109
|
+
- [ ] 4. Decide `storeIf` for post-side-effect failures; derive downstream provider keys.
|
|
110
|
+
- [ ] 5. Tests for replay, 409 overlap and 422 reuse. Build, lint, run tests, start the app.
|
|
111
|
+
|
|
112
|
+
Sources: [Idempotency keys](https://docs.nestjs.com/reliability/idempotency)
|