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

@develop-x/nest-jwt

v1.0.1

Published

基于 `jsonwebtoken` 的 NestJS JWT 模块,支持异步配置注入和双token机制(访问token + 刷新token)。

Readme

NestJS JWT 模块

基于 jsonwebtoken 的 NestJS JWT 模块,支持异步配置注入和双token机制(访问token + 刷新token)。

功能特性

  • ✅ 支持访问token和刷新token双token机制
  • ✅ 异步配置注入
  • ✅ TypeScript类型支持
  • ✅ 灵活的配置选项

安装

npm install @develop-x/nest-jwt

基本使用

1. 模块注册

同步配置

import { Module } from '@nestjs/common';
import { JwtModule } from '@develop-x/nest-jwt';

@Module({
  imports: [
    JwtModule.forRoot({
      access: {
        secret: 'your-access-secret-key',
        expiresIn: '15m',
      },
      refresh: {
        secret: 'your-refresh-secret-key', 
        expiresIn: '7d',
      },
      issuer: 'your-app',
      audience: 'your-users',
    }),
  ],
})
export class AppModule {}

异步配置(推荐)

import { Module } from '@nestjs/common';
import { JwtModule } from '@develop-x/nest-jwt';

@Module({
  imports: [
    JwtModule.forRootAsync({
      useFactory: async () => ({
        access: {
          secret: process.env.JWT_ACCESS_SECRET,
          expiresIn: process.env.JWT_ACCESS_EXPIRES_IN || '15m',
        },
        refresh: {
          secret: process.env.JWT_REFRESH_SECRET,
          expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d',
        },
        issuer: process.env.JWT_ISSUER,
        audience: process.env.JWT_AUDIENCE,
      }),
      inject: [], // 如果需要注入其他服务
    }),
  ],
})
export class AppModule {}

2. 使用JWT服务

import { Injectable } from '@nestjs/common';
import { JwtService, JwtPayload } from '@develop-x/nest-jwt';

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  async login(user: any) {
    const payload: JwtPayload = {
      sub: user.id,
      username: user.username,
      role: user.role,
    };

    // 生成token对
    return this.jwtService.generateTokenPair(payload);
  }

  async refreshTokens(refreshToken: string) {
    try {
      return this.jwtService.refreshTokenPair(refreshToken);
    } catch (error) {
      throw new Error('刷新token失败');
    }
  }

  async verifyToken(token: string) {
    const result = this.jwtService.verifyAccessToken(token);
    
    if (result.expired) {
      throw new Error('Token已过期');
    }

    return result.payload;
  }
}

API 文档

JwtModuleOptions

interface JwtModuleOptions {
  access: {
    secret: string;        // 访问token密钥
    expiresIn?: string | number; // 过期时间,默认15分钟
  };
  refresh: {
    secret: string;        // 刷新token密钥  
    expiresIn?: string | number; // 过期时间,默认7天
  };
  issuer?: string;         // 签发者
  audience?: string;       // 受众
}

JwtService 方法

  • generateAccessToken(payload: JwtPayload): string - 生成访问token
  • generateRefreshToken(payload: JwtPayload): string - 生成刷新token
  • generateTokenPair(payload: JwtPayload): JwtTokenPair - 生成token对
  • verifyAccessToken(token: string): JwtVerifyResult - 验证访问token
  • verifyRefreshToken(token: string): JwtVerifyResult - 验证刷新token
  • refreshTokenPair(refreshToken: string): JwtTokenPair - 刷新token对
  • decode(token: string): JwtPayload | null - 解码token(不验证)

接口定义

interface JwtPayload {
  sub: string;
  [key: string]: any;
}

interface JwtTokenPair {
  accessToken: string;
  refreshToken: string;
}

interface JwtVerifyResult {
  payload: JwtPayload;
  expired: boolean;
}

环境变量配置示例

# JWT 配置
JWT_ACCESS_SECRET=your-super-secret-access-key
JWT_ACCESS_EXPIRES_IN=15m
JWT_REFRESH_SECRET=your-super-secret-refresh-key  
JWT_REFRESH_EXPIRES_IN=7d
JWT_ISSUER=your-app-name
JWT_AUDIENCE=your-app-users

安全建议

  1. 访问token和刷新token使用不同的密钥
  2. 访问token设置较短的过期时间(推荐15分钟)
  3. 刷新token设置较长的过期时间(推荐7天)
  4. 密钥使用足够复杂的字符串
  5. 生产环境中密钥通过环境变量或配置服务获取
  6. 考虑实现token黑名单机制

License

MIT