Week 3 — Auth, contracts & API craft
Secure Nest APIs with JWT/RBAC, shape contracts, and craft list endpoints — then ship Notes P3 as this week’s mini-project.
- 1. JSON Web Tokens (JWT)Open
In a Nest API, JWTs are typically issued on login and read from an httpOnly cookie on every request. Bearer-header JWTs are the same token format used by mobile apps and API tooling — a useful mental model even though the browser flow here relies on cookies.
- 2. Refresh tokens & session revocationOpen
A common baseline issues a single access-token cookie that lives for a fixed expiry (say 7d) with no refresh and no server-side revocation. Use that as the baseline: understand what a refresh + rotation flow adds and why production auth usually wants it.
- 3. RBAC & guardsOpen
A common Nest setup runs two guards globally on every request: JwtAuthGuard decides who you are, RolesGuard decides what your role allows.
- 4. Middleware vs guards vs pipesOpen
Correlation ids, JWT/role checks, and DTO validation look similar — “code that runs before my controller” — but belong in different stages for a reason.
- 5. Rate limiting & throttlingOpen
Rate limiting is a judgment call about where a request cap protects the API and how Nest would enforce one. An in-memory per-IP guard is one approach — for example, throttling auth to roughly 10 attempts per 60 seconds — while @nestjs/throttler’s ThrottlerModule is the standard library approach for the same job.
- 6. CORS & credentialed requestsOpen
In a Nest API, CORS is typically enabled from a CORS_ORIGIN env value with credentials: true, which is exactly what an httpOnly-cookie auth flow needs.
- 7. DTOs & validationOpen
Use request DTOs (e.g. a CreateTicketDto/ListTicketsQueryDto) with class-validator and a global ValidationPipe.
- 8. Error contracts / HTTP exceptions → stable JSONOpen
Center this on a global exception filter (an AllExceptionsFilter) and a shared ApiErrorBody error shape.
- 9. Swagger / OpenAPI — reading /docsOpen
In a Nest API, Swagger is typically wired up in main.ts. Treat this topic as conceptual: understand what generates the document and how to read it, rather than configuring it from scratch.
- 10. Pagination & filteringOpen
Center this on a list query DTO (a ListTicketsQueryDto) and query-builder pagination in a list service.
- 11. Soft deletesOpen
Consider an API that currently hard-deletes tickets. Use that as the contrast case for understanding what a soft delete would change.
- 12. N+1 & loading strategyOpen
Center this on a Ticket→assignee relation that a list query does not join — a natural place N+1 could creep in.
- 13. File handling: Node fs & Nest uploadsOpen
A typical Nest upload slice ties these together: a controller accepts an upload with FileInterceptor, a service writes the bytes with fs/promises, and an attachment entity stores the storage_key and metadata.
- 14. Project planning & ERDOpen
Schema mistakes are the most expensive to undo, because data and every query, DTO, and screen already depend on them. Planning the entities and relationships first — as an ERD — makes those decisions explicit and cheap to change while they are still just a sketch.
- 15. Core API vertical-slice checklistOpen
Use a tickets-style endpoint set as the example: when every route satisfies this checklist, it makes a good template for a new one.
- 16. Notes API — Auth + list craft milestoneOpen
Maps to Week 3 auth and API craft. Follow standard cookie JWT + RolesGuard patterns.
End-of-week mini-project · practice only
Community Blog API (auth, RBAC & API craft)
A secured blog/forum API: cookie JWT login, roles, validated posts, paginated feeds, soft deletes, and image uploads.
Definition
A production-shaped Nest API where authenticated users publish posts and comments, guarded by RBAC and hardened with validation, rate limiting, CORS, stable errors, and Swagger docs.
In simpler words
Build the backend of a small blog where people log in, write posts with cover images, and browse a paged feed — with admins able to moderate.
Concepts covered this week
- JSON Web Tokens (JWT)
- Login issues an httpOnly access-token cookie verified by a JwtAuthGuard.
- Refresh tokens & session revocation
- A rotating refresh endpoint; logout revokes the session.
- RBAC & guards
- reader/author/admin roles; a RolesGuard lets admins moderate any post.
- Middleware vs guards vs pipes
- Correlation-id middleware, auth/roles guards, and a validation pipe each do one job.
- Rate limiting & throttling
- Throttle login and comment creation to blunt abuse (429 + Retry-After).
- CORS & credentialed requests
- enableCors({ credentials: true }) for the web origin so the cookie flows.
- DTOs & validation
- CreatePostDto/CreateCommentDto with class-validator + whitelist.
- Error contracts
- A global exception filter returns a stable JSON error shape.
- Swagger / OpenAPI
- Decorate endpoints and expose /docs with cookie auth.
- Pagination & filtering
- GET /posts?page&limit&tag&author returns { data, meta }.
- Soft deletes
- Deleting a post hides it from feeds and counts without dropping the row.
- N+1 & loading strategy
- Load post authors and comment counts with joins, not per-row queries.
- File handling: Node fs & Nest uploads
- A FileInterceptor accepts a cover image and stores it via fs.
- Project planning & ERD
- Plan users/posts/comments/tags relations before coding.
- Core API vertical-slice checklist
- Apply the vertical-slice checklist to the posts resource end to end.
Deliverables
- Cookie JWT login + refresh rotation + logout (revocation)
- RBAC: authors edit their own posts; admins moderate any
- Validated CRUD for posts/comments with a global error filter + Swagger docs
- Paginated, filterable, soft-delete-safe feed with cover-image uploads (no N+1)
Build guide
- Plan the ERDModel users, posts, comments, tags (posts↔tags N:N) and note ownership rules before writing code.
- Stand up authLogin sets an httpOnly access cookie; add a refresh endpoint that rotates tokens and a logout that revokes the session.
- Add RBACJwtAuthGuard + RolesGuard with reader/author/admin; enforce owner-or-admin on edit/delete.
- Validate + standardize errorsAdd DTOs with class-validator and a global exception filter that returns a consistent error JSON.
- Build the feedGET /posts with page/limit/tag/author filters returning { data, meta }; exclude soft-deleted rows from data and total.
- Kill N+1Load authors and comment counts via joins/relations so the feed runs a fixed number of queries.
- Accept uploadsUse FileInterceptor for a cover image, validate type/size, and store it with a sanitized filename.
- Harden + documentAdd throttling to login/comments, enable credentialed CORS, and expose Swagger /docs.
Acceptance checklist
- [ ] httpOnly cookie login + refresh rotation + logout revokes session
- [ ] Owner-or-admin enforced by RolesGuard (401 vs 403 correct)
- [ ] DTO validation + global error filter return stable JSON
- [ ] GET /posts paginates, filters, and hides soft-deleted rows in data AND total
- [ ] Cover-image upload validates type/size; feed has no N+1
- [ ] Throttling, credentialed CORS, and Swagger /docs in placeStretch goals
- Add reactions (like/bookmark) as an N:N relation.
- Add full-text search on post titles/bodies.
- Add an audit log of moderation actions.
Tips
- 401 = not authenticated; 403 = authenticated but wrong role.
- Reuse the same query filters for the page and the count so totals never drift.