typescript
53 lines · 7 steps
How a GraphQL auth guard works in NestJS
A NestJS guard extracts a JWT from GraphQL requests, verifies it, and enforces role-based access before a resolver runs.
Explained by
highlit
1import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
2import { GqlExecutionContext } from '@nestjs/graphql';
3import { Reflector } from '@nestjs/core';
4import { JwtService } from '@nestjs/jwt';
5
6type GqlContext = {
7 req: {
8 headers: Record<string, string | undefined>;
9 user?: { id: string; roles: string[] };
10 };
11};
12
13@Injectable()
14export class GqlAuthGuard implements CanActivate {
15 constructor(
16 private readonly reflector: Reflector,
17 private readonly jwtService: JwtService,
18 ) {}
19
20 async canActivate(context: ExecutionContext): Promise<boolean> {
21 const gqlContext = GqlExecutionContext.create(context);
22 const ctx = gqlContext.getContext<GqlContext>();
23 const { req } = ctx;
24
25 const token = this.extractToken(req.headers.authorization);
26 if (!token) {
27 throw new UnauthorizedException('Missing bearer token');
28 }
29
30 try {
31 const payload = await this.jwtService.verifyAsync<{ sub: string; roles: string[] }>(token);
32 req.user = { id: payload.sub, roles: payload.roles ?? [] };
33 } catch {
34 throw new UnauthorizedException('Invalid or expired token');
35 }
36
37 const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
38 gqlContext.getHandler(),
39 gqlContext.getClass(),
40 ]);
41
42 if (requiredRoles?.length && !requiredRoles.some((role) => req.user!.roles.includes(role))) {
43 throw new UnauthorizedException('Insufficient permissions');
44 }
45
46 return true;
47 }
48
49 private extractToken(header?: string): string | null {
50 const [scheme, value] = header?.split(' ') ?? [];
51 return scheme === 'Bearer' && value ? value : null;
52 }
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A guard is the single choke point where you can reject a request before any resolver logic runs.
- 2GraphQL contexts must be unwrapped with GqlExecutionContext before you can reach the underlying HTTP request.
- 3Reading metadata off both the handler and class lets one guard enforce declarative role requirements.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-graphql-auth-guard-works-in-nestjs-explained-typescript-b11b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.