Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

373
Vistas
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;
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I wasted a lot of time tying to get this to work. The weird thing is that this will work in the api itself.

So instead of calling firebase-admin action in the _middleware file. Call it in the api itself like:

import type { NextApiRequest, NextApiResponse } from 'next'
import { auth } from "../../firebase/auth-admin";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const authorization = req.headers.authorization
  console.log(`Handler auth header: ${authorization}`)

  if (!authorization) {
    return res.status(401).json({ message: 'Authorisation header not found.' })
  }

  const token = authorization.split(' ')[1]
  if (!token) {
    return res.status(401).json({ message: 'Bearer token not found.' })
  }

  console.log(`Token: ${token}`)

  try {
    const {uid} = await auth.verifyIdToken("sd" + token)
    console.log(`User uid: ${uid}`)
    res.status(200).json({ userId: uid })
  } catch (error) {
    console.log(`verifyIdToken error: ${error}`)
    res.status(401).json({ message: `Error while verifying token. Error: ${error}` })
  }
}

A workaround to make this reusable is to create a wrapper function.

If anyone knows how to make this work in a _middleware file, I would be really grateful.

Edit: Gist for the wrapper middleware function: https://gist.github.com/jvgrootveld/ed1863f0beddc1cc2bf2d3593dedb6da

about 4 years ago · Juan Pablo Isaza Denunciar

0

make sure you're not calling firebase-admin in the client

import * as admin from "firebase-admin";
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda