Next.js 中间件模块未找到:无法解析“fs”

me-*_*-me 5 javascript firebase-admin next.js

_middleware当我尝试初始化 Firebase admin V9 时,在 Next.js 文件中出现此错误。有人知道如何解决这个问题吗?

./node_modules/@google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
Run Code Online (Sandbox Code Playgroud)

../../firebase/auth-admin

import * as admin from "firebase-admin";

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY,
    }),
  });
}

const firestore = admin.firestore();

const auth = admin.auth();

export { firestore, auth };
Run Code Online (Sandbox Code Playgroud)

在我的中调用它_middleware

import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { auth } from "../../firebase/auth-admin";

export default async function authenticate(
  req: NextRequest,
  ev: NextFetchEvent
) {
  const token = req.headers.get("token");
  console.log("auth = ", auth);
  //   const decodeToken = await auth.verifyIdToken(token);
  return NextResponse.next();
}
Run Code Online (Sandbox Code Playgroud)

在这里看到了一个通过自定义 webpack 的解决方案,但这并不能解决问题。

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config, { isServer, node }) => {
    node = {
      ...node,
      fs: "empty",
      child_process: "empty",
      net: "empty",
      tls: "empty",
    };
    return config;
  },
};

module.exports = nextConfig;
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 12

Next.js 中间件使用的 Edge Runtime 不支持 Node.js 本机 API。

来自Edge 运行时文档:

Edge Runtime 有一些限制,包括:

  • 不支持本机 Node.js API 。例如,您无法读取或写入文件系统
  • 可以使用Node 模块,只要它们实现 ES 模块并且不使用任何原生 Node.js API

您不能使用fsNext.js 中间件中使用的 Node.js 库。尝试使用客户端库。