javascriptnext.jsfirebase-admin

Next.js middleware Module not found: Can't resolve 'fs'


Getting this error in Next.js _middleware file when I try to initialize Firebase admin V9. Anyone know how to solve this issue?

./node_modules/@google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'

../../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 };

Calling it in my _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();
}

I saw a solution here by customizing webpack but this does not fix it.

/** @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;

Solution

  • The Edge Runtime, which is used by Next.js Middleware, does not support Node.js native APIs.

    From the Edge Runtime documentation:

    The Edge Runtime has some restrictions including:

    • Native Node.js APIs are not supported. For example, you can't read or write to the filesystem
    • Node Modules can be used, as long as they implement ES Modules and do not use any native Node.js APIs

    You can't use Node.js libraries that use fs in Next.js Middleware. Try using a client-side library instead.