nestjs/nest · error · UnauthorizedException

Unauthorized

Error message

Unauthorized

What it means

Thrown by a GraphQL auth guard (integration fixture) via NestJS `UnauthorizedException` (HTTP 401). The guard calls `GqlExecutionContext.create(context)` and unconditionally throws whenever a GraphQL context exists, demonstrating how to reject unauthenticated GraphQL requests. Because the created context object is always truthy, this fixture always rejects.

Source

Thrown at integration/graphql-code-first/src/common/guards/auth.guard.ts:14

import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';

@Injectable()
export class AuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const gqlContext = GqlExecutionContext.create(context);
    if (gqlContext) {
      throw new UnauthorizedException();
    }
    return true;
  }
}

View on GitHub (pinned to 6ec0e2783d)

Solutions

  1. If this is your own guard, replace `if (gqlContext)` with a real authentication check (e.g. validate a JWT or session from `context.getContext().req.headers.authorization`).
  2. If you are running the integration test, send the request the test expects (no/invalid credentials) and assert the 401.
  3. Ensure the guard is only applied where authentication is actually required.

Example fix

// before
async canActivate(context: ExecutionContext): Promise<boolean> {
  const gqlContext = GqlExecutionContext.create(context);
  if (gqlContext) {
    throw new UnauthorizedException();
  }
  return true;
}
// after
async canActivate(context: ExecutionContext): Promise<boolean> {
  const ctx = GqlExecutionContext.create(context).getContext();
  const authHeader = ctx.req?.headers?.authorization;
  if (!authHeader) {
    throw new UnauthorizedException('Missing auth token');
  }
  return true;
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Validate auth before invoking a guarded resolver from the client
const res = await fetch('/graphql', {
  method: 'POST',
  headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
  body: JSON.stringify({ query: '{ recipe(id:"1"){ id } }' }),
});
if (res.status === 401) { /* re-login */ }

Type guard

import { UnauthorizedException } from '@nestjs/common';
function isUnauthorized(e: unknown): e is UnauthorizedException {
  return e instanceof UnauthorizedException;
}

Try / catch

try {
  return await this.recipesService.findOneById(id);
} catch (e) {
  if (e instanceof UnauthorizedException) {
    // redirect to login
  }
  throw e;
}

Prevention

When it happens

Trigger: Executing any resolver method decorated with `@UseGuards(AuthGuard)` — e.g. the `recipe(id: String!)` query in recipes.resolver.ts:18 — against this integration fixture.

Common situations: Integration/e2e tests asserting that GraphQL guards emit a 401; copying this fixture into real code without replacing the stub condition with real auth checks.

Related errors


AI-assisted analysis of nestjs/nest@6ec0e2783d (2026-08-03). Data as JSON: /data/errors/21fcfc82886bd754.json. Report an issue: GitHub.