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

Next.js使用_middleware.ts时遇Module not found: Can't resolve 'crypto'错误

Next.js中间件校验JWT时出现"Can't resolve 'crypto'"错误的解决办法

错误原因

Next.js的中间件运行在Edge Runtime环境中,该环境不支持Node.js的内置crypto模块,而你使用的jsonwebtoken库依赖Node.js的crypto模块,因此触发了模块找不到的错误。

解决方案

方案一:改用Edge友好的jose库(推荐)

jose库基于Web Crypto API实现,完全兼容Edge Runtime,是Next.js中间件处理JWT的首选方案。

  1. 安装jose:
npm install jose
# 或
yarn add jose
  1. 修改中间件代码:
import { jwtVerify } from 'jose';
import { NextRequest, NextResponse } from 'next/server';

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const token = req.cookies.get('auth')?.value;

  if (pathname.includes('/admin/dashboard')) {
    if (!token) {
      return NextResponse.redirect(new URL('/', req.url));
    }
    try {
      // 将JWT密钥转换为Uint8Array(jose要求的格式)
      const secret = new TextEncoder().encode(process.env.JWT_SECRET as string);
      await jwtVerify(token, secret);
      return NextResponse.next();
    } catch (err) {
      return NextResponse.redirect(new URL('/signin', req.url));
    }
  }
  return NextResponse.next();
}

方案二:为jsonwebtoken添加polyfill(不推荐)

如果坚持使用jsonwebtoken,可以通过Webpack配置添加crypto的polyfill,但这种方法在Edge Runtime下可能存在兼容性问题,仅作为备选方案。

  1. 安装polyfill依赖:
npm install crypto-browserify
# 或
yarn add crypto-browserify
  1. 修改next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.resolve.fallback = {
      ...config.resolve.fallback,
      crypto: require.resolve('crypto-browserify'),
    };
    return config;
  },
};

module.exports = nextConfig;

内容的提问来源于stack exchange,提问作者Sujon Hossain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:30:39