npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@relab/nestjs-auth

v1.2.0

Published

Auth helpers for Nest.js

Downloads

379

Readme

@relab/nestjs-auth

Authentication and authorization helpers for NestJS (Fastify) applications. Provides decorators and guards for JWT authentication and role-based access control, with support for extracting the current user from requests.

Features

  • BaseAuth: Factory for creating a project-specific Auth decorator for JWT authentication and role-based access control.
  • Auth: (Recommended) Your own pre-configured decorator for authentication and authorization, created using BaseAuth.
  • CurrentUser: Parameter decorator to access the current authenticated user from the request.
  • JwtGuard: Guard for JWT authentication, compatible with Fastify and GraphQL.
  • createRolesGuard: Factory for creating custom role guards.
  • SocketAuth: Middleware for authenticating Socket.IO connections using JWT tokens from headers or cookies.

Installation

pnpm add @relab/nestjs-auth
# or
yarn add @relab/nestjs-auth
# or
npm install @relab/nestjs-auth

Note: This package is designed for use with NestJS and Fastify. Make sure you have @nestjs/common, @nestjs/core, @nestjs/passport, @nestjs/graphql, fastify, and rxjs installed as peer dependencies.

Usage

Creating a Project-wide Auth Decorator

For better type safety and convenience, you can create a project-specific Auth decorator using the BaseAuth factory. This allows you to define your user and role types once and use the Auth decorator throughout your application:

// auth.decorator.ts
import { BaseAuth } from '@relab/nestjs-auth';
import { Role } from './role.enum';
import { CurrentUserDto } from './current-user.dto';

export const Auth = BaseAuth<Role, CurrentUserDto>(user => user?.role);

You can now use your custom Auth decorator in controllers:

import { Controller, Get } from '@nestjs/common';
import { Auth, CurrentUser } from './auth.decorator';
import { CurrentUserDto } from './current-user.dto';

@Controller('profile')
export class ProfileController {
  // JWT authentication only
  @Get('me')
  @Auth()
  getMe(@CurrentUser() user: CurrentUserDto) {
    return user;
  }

  // JWT authentication + role-based access
  @Get('admin')
  @Auth('admin')
  getAdminData(@CurrentUser() user: CurrentUserDto) {
    return { admin: true, user };
  }
}

Custom Role Guard

You can create a custom roles guard using createRolesGuard if you need advanced role resolution logic:

import { createRolesGuard } from '@relab/nestjs-auth';
import { UseGuards } from '@nestjs/common';

const MyRolesGuard = createRolesGuard((user) => user?.role);

@UseGuards(MyRolesGuard)
class SomeController {}

Example: Using SocketAuth in a NestJS Gateway

For a more idiomatic NestJS approach, you can use SocketAuth directly in your WebSocket gateway:

import { WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';
import { SocketAuth } from '@relab/nestjs-auth';

@WebSocketGateway()
export class WebsocketsGateway implements OnGatewayInit<Server>, OnGatewayConnection<Socket>, OnGatewayDisconnect<Socket> {
  @WebSocketServer()
  server: Server;

  constructor(private readonly jwtService: JwtService) {}

  afterInit(server: Server) {
    server.use(SocketAuth(this.jwtService));
  }

  handleConnection(client: Socket) {
    // Access the authenticated user:
    const user = client.data.user;
    // ...
  }

  handleDisconnect(client: Socket) {
    // ...
  }
}

This approach ensures that all incoming socket connections are authenticated using JWT, and the user payload is available on client.data.user in your gateway handlers.

API Reference

BaseAuth(resolveRole: (user: TUser | undefined) => TRole | undefined)

  • Factory function to create a project-specific Auth decorator.
  • Returns a decorator: (...roles: TRole[]) => MethodDecorator & ClassDecorator.
  • If roles are provided, only users with matching roles can access the route.
  • resolveRole is a function to extract the role from the user object.

Auth(...roles: TRole[])

  • Your project-specific decorator, created using BaseAuth.
  • Use with or without roles for authentication and authorization.

CurrentUser()

  • Parameter decorator to access the current authenticated user from the request.
  • Returns undefined if no user is present.

JwtGuard

  • Guard for JWT authentication, compatible with Fastify and GraphQL.
  • Can be used directly with @UseGuards(JwtGuard).

createRolesGuard(resolveRole)

  • Factory function to create a custom role guard.
  • resolveRole is a function to extract the role from the user object.

SocketAuth(jwtService)

  • Middleware for authenticating Socket.IO connections using JWT.
  • Accepts a JwtService instance.
  • Checks for a JWT token in the Authorization header (as Bearer <token>) or in a cookie named access_token.
  • On success, attaches the decoded user to socket.data.user. Calls next() on success, or passes an UnauthorizedException to next() on failure.

License

MIT