You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt3中使用jsonwebtoken鉴权报错util.inherits不是函数求助

解决Nuxt.js v3中jsonwebtoken库"util.inherits is not a function"报错问题

原因说明

jsonwebtoken库依赖Node.js CommonJS环境下的旧API util.inherits,而Nuxt 3的Nitro运行时默认更偏向ES模块和跨平台兼容(支持Edge Runtime等场景),这些旧Node.js API可能未被默认提供,导致调用时崩溃。

解决方案

方案1:改用现代JWT库(推荐)

放弃使用jsonwebtoken,选择支持ES模块、无旧API依赖的现代JWT库,比如jose或@auth/core/jwt,它们完全适配Nuxt 3的环境。

以jose为例:

  1. 安装依赖:
npm install jose
# 或 yarn add jose
  1. 生成JWT示例:
import { SignJWT } from 'jose'

async function generateJwt(payload) {
  const secretKey = new TextEncoder().encode(process.env.JWT_SECRET)
  return await new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('24h')
    .sign(secretKey)
}
  1. 验证JWT示例:
import { jwtVerify } from 'jose'

async function verifyJwt(token) {
  const secretKey = new TextEncoder().encode(process.env.JWT_SECRET)
  const { payload } = await jwtVerify(token, secretKey)
  return payload
}

方案2:修复jsonwebtoken的兼容问题(仅用于必须保留该库的场景)

如果一定要继续使用jsonwebtoken,可以通过配置Nuxt来提供缺失的API支持:

  1. 升级jsonwebtoken到最新版本:
npm install jsonwebtoken@latest
  1. 在nuxt.config.ts中启用Node.js兼容模式:
export default defineNuxtConfig({
  nitro: {
    nodejsCompat: true
  }
})
  1. 若仍报错,添加util polyfill:
    • 安装polyfill依赖:
    npm install util
    
    • 创建插件文件plugins/polyfill.util.ts:
    import util from 'util'
    globalThis.util = util
    
    • 在nuxt.config.ts中注册插件:
    export default defineNuxtConfig({
      plugins: ['~/plugins/polyfill.util.ts'],
      nitro: {
        nodejsCompat: true
      }
    })
    

内容的提问来源于stack exchange,提问作者m.mikolajczak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:20:32