Today I'm excited to announce two new packages: @nestjs/authentication and @nestjs/authorization. The first one signs users in and tells the rest of your application who they are, with sessions, password hashing, email verification, password resets, two-factor authentication, magic links, OpenID Connect, access and refresh tokens, and API keys. The second one decides what those users are allowed to do, with type-safe policies that work with any data shape.
In case you're not familiar with NestJS, it is a TypeScript Node.js framework that helps you build enterprise-grade efficient and scalable Node.js applications.
Let's dive right in! 🐈
Why new auth packages?
Authentication is probably the most rewritten piece of code in the entire Node.js ecosystem. Every project needs it, and every project ends up assembling it from scratch: a Passport strategy here, a JWT library there, a hand-rolled password reset flow, and a roles.includes('admin') check copied into twenty controllers.
The trouble is that auth is also where the details matter most. Is the session cookie HttpOnly, Secure, and SameSite? Is the token in the database hashed? Does the reset link expire, and does it stop working once the password changes? Does "forgot password" reveal whether an account exists? Does a deleted user lose access right away, or only when their token expires? Can a customer see someone else's order by changing the id in the URL? Each of these is easy to get wrong, and each one only shows up when someone exploits it.
These two packages take care of those details, so you don't have to rediscover them in every project. They're built on Node.js built-ins, and all state lives in your own database.
Throughout this post, we'll build the auth layer of an online store for cat food and supplies. Guests browse products, customers place and view their own orders, staff manage products and issue refunds (up to a limit), admins can do (almost) anything, and partners integrate through API keys.
Part 1: Authentication
Getting started
First, install the package:
$ npm i --save @nestjs/authenticationand register the module:
@Module({ imports: [ AuthenticationModule.forRoot({ session: { absoluteTtl: '14d', // signed out after 14 days, however active idleTtl: '3d', // or after 3 days without a request }, }), AuthModule, ],})export class AppModule {}Next, tell the module how to find a user for a session. That's a provider class:
@Injectable()export class SessionAuth extends SessionCookieProvider<User> { constructor( registry: AuthenticationRegistry, private readonly usersRepository: UsersRepository, ) { super(); registry.registerProvider(this); } validate(session: SessionRecord) { return this.usersRepository.findById(session.userId); }}validate() runs on every authenticated request, so a user you delete or block loses access immediately. Return null, and the session ends.
The module registers a global guard, so every route requires a signed-in user by default. To open one up, mark it with @Public(). To read the user, use @CurrentUser() (or @CurrentUser('id') for a single property, and @CurrentSession() for the session itself):
@Controller('me')export class MeController { @Get() me(@CurrentUser() user: User) { return user; }}Deeper in your code, services can read the current user from AuthenticationContext, so you don't have to pass it through every method signature. And with a small type augmentation (AuthenticationTypes), @CurrentUser() and the context are typed with your own User everywhere.
Sign-up and sign-in
Signing a user in, once you've verified their credentials, is a single call:
@Public()@Post('sign-in')@HttpCode(200)async signIn(@Body() dto: SignInDto) { const user = await this.credentials.verify(dto.email, dto.password); if (!user) { throw new UnauthorizedException('Invalid email or password'); } const session = await this.signInService.signIn(user.id, { method: 'password' }); return { mfaRequired: session.mfa === 'pending' };}Here's what you get with that, without writing a single extra line:
- The session cookie (
__Host-sid) holds a random 256-bit token, and it'sHttpOnly,Secure, andSameSite=Lax. Only a SHA-256 hash of the token is stored, so a leaked database doesn't leak sessions. - Session fixation is handled. Signing in deletes the browser's previous session.
- CSRF is handled, too. Cross-site, state-changing requests are treated as anonymous, based on
Sec-Fetch-Site,Origin, andHost, and a cross-site sign-in is refused (login CSRF). If your web app lives on a different origin, list it insession.trustedOrigins.
Passwords are hashed with PasswordHasher using scrypt (about 128 MiB of memory per hash, run on the libuv thread pool, so it doesn't block the event loop), with its parameters recorded in each hash. When you raise the cost later, needsRehash() tells you which hashes to upgrade on the next successful sign-in. And when nobody has the email that was entered, verification still checks a dummy hash, so response times don't reveal which accounts exist.
Email verification and password resets
Both flows are handlers you plug in, and they pair perfectly with @nestjs/mail:
@Injectable()export class PasswordResetMailer extends PasswordResetHandler<User> { constructor( registry: AuthenticationRegistry, private readonly mailer: Mailer, private readonly usersRepository: UsersRepository, ) { super(); registry.registerHandler('passwordReset', this); } // findUser(), send(), and updatePassword()}The controller is tiny:
@Public()@Controller('auth/password')export class PasswordResetController { @Post('forgot') @HttpCode(202) forgot(@Body() { email }: EmailDto) { void this.passwordResetService.request(email); } @Post('reset') @HttpCode(200) async reset(@Body() { token, password }: ResetPasswordDto) { // throws when the link is invalid or expired return this.passwordResetService.reset(token, password, { signIn: true }); }}The module takes care of the parts that are easy to get wrong:
- A verification link works once, for 24 hours, and only for the address it was sent to. Change the email, and the account becomes unverified again.
- A reset link works once, for an hour, and only while the account still has the same address and password.
- Resetting a password ends every session and refresh token, so an attacker who had access is kicked out. And since the user just proved they control the inbox, the address is marked as verified.
request()responds before it even looks up the address, so "forgot password" answers the same way, at the same speed, whether the account exists or not.- With
signIn: true, the user is signed in after the reset, but two-factor authentication still applies.
Tokens for the mobile app
Browsers get cookies, but your mobile app wants tokens. Add a JwtBearerProvider, and issue tokens after verifying the credentials:
@Injectable()export class JwtAuth extends JwtBearerProvider<User> { constructor(registry: AuthenticationRegistry, private readonly users: UsersRepository) { super({ realm: 'store' }); registry.registerProvider(this); } validate({ sub }: { sub: string }) { return this.users.findById(sub); }}return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] },});Access tokens are short-lived (we configured ttl: '15m'), and refresh tokens rotate: each one can be used exactly once. If an old refresh token shows up again, which only happens when it was stolen, the whole token family is revoked, for the thief and the legitimate app alike.
‼️ A small trap the module protects you from: @nestjs/jwt counts lifetimes in seconds, while this module accepts milliseconds or readable strings like '15m'. A numeric lifetime under a minute logs a warning at startup, because 3600 means 3.6 seconds here, not an hour. ‼️
Two-factor authentication, magic links, and Google
Once the basics are in place, the rest is mostly configuration and a handful of routes:
- TOTP two-factor authentication with recovery codes. After a password sign-in, the session is
pending(that's themfaRequiredflag from earlier) and only becomes a full session once the user enters a code. Secrets are encrypted at rest. - Magic links, which work once, for 15 minutes.
- "Sign in with Google", or any other OpenID Connect provider, with the login transaction protected against tampering.
- Session management, so customers can list their sessions, revoke one ("that's not my phone!"), or sign out everywhere.
Every one of these flows also works for GraphQL (queries, mutations, and subscriptions) and WebSockets, where a connection without a signed-in user is closed with code 1008.
API keys for partners
Resellers want to integrate with your store's API without a browser. API keys are just another provider:
@Injectable()export class ApiKeyAuth extends ApiKeyProvider<User> { constructor(registry: AuthenticationRegistry, private readonly apiKeys: ApiKeysRepository) { super({ prefix: 'cat', realm: 'store' }); registry.registerProvider(this, { order: 2 }); } findKey(id: string) { return this.apiKeys.findWithUser(id); // { hash, user, expiresAt } or null }}Keys carry a recognizable prefix (handy for secret scanners), are stored as hashes, and expire after a year. A lost key is revoked, never recovered, and the response that creates a key is the only one that ever shows it.
There's one subtle rule worth copying from the docs: keys shouldn't be able to manage other keys. Otherwise, a single leaked key could mint new ones forever. So the key management routes accept only sessions:
@Authenticate({ providers: [SessionAuth] })@Controller('auth/api-keys')export class ApiKeysController { // POST to create, GET to list, DELETE to revoke}Your database, your schema
Sessions, refresh tokens, TOTP secrets, and one-time links all live in your own database, through a store you register. The documentation includes complete Drizzle and TypeORM stores, and the module refuses to start in production without one. One detail from the TypeORM store is worth repeating: it uses conditional UPDATE and DELETE statements, never save(), because save() could write back a session that a sign-out deleted a millisecond earlier.
Part 2: Authorization
Policies, not role checks
Now that we know who the user is, let's decide what they can do. Install the second package:
$ npm i --save @nestjs/authorizationand register its module, after the authentication one, since authorization reads the user that authentication sets:
@Module({ imports: [ AuthenticationModule.forRootAsync({ /* ... */ }), AuthorizationModule.forRoot(), ],})export class AppModule {}(And if you get the order wrong, the application refuses to start and tells you why.)
Permissions are expressed as policies: classes whose methods answer "may this user do this?":
@Policy()export class ProductPolicy { view(user: User | null, product: Product) { return product.published || isStaff(user); } viewDrafts(user: User | null) { return isStaff(user); } create(user: User | null) { return isStaff(user); } update(user: User | null) { return isStaff(user); }}Policies are plain methods over plain data, so they work with Prisma, Drizzle, Kysely, or anything else. No entity classes, no special query language, and every rule about products lives in one file. Also, only a literal true allows. Any other value, even a truthy one, denies, so a policy that accidentally returns a user object or a non-empty string fails closed.
Check routes
Route-level checks go on the handler with @Can():
@Controller('products')export class ProductsController { @Get(':id') @Authenticate({ optional: true }) @Can.Anyone() findOne(@CurrentUser() user: User | null, @Param('id') id: string) { return this.productsService.findOne(user, id); } @Post() @Can(ProductPolicy, 'create') create(@Body() dto: CreateProductDto) { return this.productsService.create(dto); }}And here's my favorite part: it's type-safe. @Can(ProductPolicy, 'craete') doesn't compile. Neither does @Can(ProductPolicy, 'view'), because view needs the product, and a route doesn't have it yet. The compiler only offers abilities whose arguments the route can actually provide, so you find these mistakes in your editor, not in a pen test report.
The global guard also denies by default. A route runs only if it declares @Can(), @Can.Anyone(), or @Public(). Forget to declare anything, and the route is closed, not open. Startup logs even name the handlers you forgot about.
Check records
Some checks need the record itself. "Customers can only see their own orders" can't be decided before the order is loaded, so those checks go in the service:
@Policy()export class OrderPolicy { viewAll(user: User) { return isStaff(user); } view(user: User, order: Order) { return order.userId === user.id || isStaff(user); } refund(user: User, order: Order) { return isStaff(user) && order.status === 'paid'; }}async findOne(user: User, id: string) { const order = await this.findById(id); await this.authorization.authorize(OrderPolicy, 'view', user, order); return order;}authorize() throws when access is denied, while can() returns true or false. That makes can() perfect for two very common tasks:
- Filtering lists. Don't load every order and filter in memory. Ask the policy once, and filter in the query:async findAll(user: User) {return (await this.authorization.can(OrderPolicy, 'viewAll', user))? this.orders.findAll(): this.orders.findByUser(user.id);}
- Telling the UI what's possible. Add a
canRefundflag to each order, computed by the same policy that guards the refund itself, and the frontend never has to duplicate your rules:return { ...order, canRefund: await this.authorization.can(OrderPolicy, 'refund', user, order) };
‼️ A 403 on /orders/123 tells the caller that order 123 exists. When that matters, check with can() and throw NotFoundException instead. ‼️
Check route parameters
Sometimes the decision only needs a value from the URL. For /customers/:customerId/orders, the third argument of @Can() extracts it, and the check runs before any pipe or handler:
@Controller('customers/:customerId/orders')export class CustomerOrdersController { @Get() @Can(OrderPolicy, 'viewOrdersOf', (context) => [ context.switchToHttp().getRequest().params.customerId, ]) findAll(@Param('customerId') customerId: string) { return this.ordersService.findByUser(customerId); }}Admins, and services in policies
Admins usually can do anything, but special-casing them in every method gets old quickly. A policy's before() hook runs first and can short-circuit the decision:
@Policy()export class ProductPolicy implements PolicyBefore<User> { before(user: User | null) { if (user?.roles.includes('admin')) { return true; } } // ...}Note that OrderPolicy has no such hook, on purpose. "Nobody refunds a shipped order" should apply to admins, too.
Policies are also regular providers, so they can inject services. Let's say each staff member can refund up to a personal limit:
@Policy()export class OrderPolicy { constructor(private readonly refundLimits: RefundLimitsService) {} async refund(user: User, order: Order) { if (!isStaff(user) || order.status !== 'paid') { return false; } return order.total <= (await this.refundLimits.maxRefundFor(user)); }}The ability simply becomes async, and nothing else changes: not the controller, not the service, not the tests calling authorize().
Guests, 401s, and 403s
Guests arrive as null, which is why route abilities take User | null. With @Authenticate({ optional: true }), a guest can browse published products while staff also sees drafts, all decided by the same ProductPolicy.
The status codes follow a simple rule. A guest who's denied gets 401, because signing in might change the answer. A signed-in user who's denied gets 403. And the 403 body never names the ability that failed, so you don't leak your permission model to curious clients. The same errors work over GraphQL (UNAUTHENTICATED and FORBIDDEN), WebSockets, and microservices.
Auditing
Every denial is published on AuthorizationEvents.events$ and the nestjs:authorization:denied diagnostics channel, with the policy, ability, reason, and user. That's an audit log of who tried what and was refused, one subscription away. Just log only the fields you need, since the payload includes the user.
Use cases
To sum up, here's how the pieces map to the problems you'll actually face:
- A web app with a mobile app. Sessions for the browser, short-lived JWTs with rotating refresh tokens for mobile, and the same policies for both.
- An e-commerce or SaaS back office. Roles like staff and admin in
before(), per-person limits through injected services, and record-level checks in services. - Multi-tenant APIs. "Users can only see their own organization's data" is a record check, or a route parameter check for nested URLs, plus filtering in the query.
- Public APIs for partners. API keys with a prefix, an expiry, and no power to mint new keys.
- Content with drafts. Optional authentication and a policy that decides what guests see versus what staff see.
Testing
Policies are plain classes, so unit testing them is just calling their methods:
it('lets staff refund paid orders within their limit', async () => { const policy = new OrderPolicy(refundLimits); vi.spyOn(refundLimits, 'maxRefundFor').mockResolvedValue(10_000); expect(await policy.refund(sam, alicePaid)).toBe(true); expect(await policy.refund(sam, aliceShipped)).toBe(false);});Calling an ability directly skips before(), so test admin behavior through AuthorizationService, and test the 401 and 403 mapping through HTTP. For the full flow, the documentation shows end-to-end tests with PGlite, InMemoryMailTransport from @nestjs/mail to catch verification and reset emails, and a cheaper PasswordHasher configuration so tests stay fast.
A few production tips
Both chapters end with a production checklist, but here are the items I'd underline:
- Never cache responses by URL on routes that check records. A
CacheInterceptorwould happily serve Bob's order to Alice. - Re-check state at write time. Make the refund itself conditional (only update where the status is still
paid), and use an idempotency key with the payment provider. - Review every
@Can.Anyone(). It's the one place where the default deny is switched off, so make sure the service behind it authorizes. - Serve over HTTPS and call
app.enableCsrfProtection()(Nest 12.1+), and keep secrets such as the JWT and TOTP keys in a secret manager.
Try it today!
$ npm i --save @nestjs/authentication @nestjs/authorizationThe new Authentication and Authorization chapters in the official documentation cover everything above in depth, including the database stores, two-factor authentication, OpenID Connect, GraphQL and WebSockets, and the full production checklists. Give them a try, and please open an issue if anything gets in your way!
Happy coding! 🐈
Learn NestJS - Official NestJS Courses 📚
Level-up your NestJS and Node.js ecosystem skills in these incremental workshop-style courses, from the NestJS Creator himself, and help support the NestJS framework! 🐈🚀 The NestJS Fundamentals Course is now LIVE and 25% off for a limited time!
🎉 NEW - NestJS Course Extensions now live!
- NestJS Advanced Concepts Course now LIVE!
- NestJS Advanced Bundle (Advanced Architecture and Advanced Concepts) now 22% OFF!
- NestJS Microservices now LIVE!
- NestJS Authentication / Authorization Course now LIVE!
- NestJS GraphQL Course (code-first & schema-first approaches) are now LIVE!
- NestJS Authentication / Authorization Course now LIVE!
