Search code examples
typescriptfirebasenext.jsfirebase-adminnext.js13

Middleware doesnt work with firebase-admin module beucase of OS Module


I have a big problem. I'm currently implementing an authentication and verification middleware for my api. But the problem is that firebase-admin uses modules that aren't capable to run in nextjs because they are Edge Runtime modules. Now I'm always getting the Error: The edge runtime does not support Node.js 'os' module. error message.

This is the tracestack:

Server Error

Error: The edge runtime does not support Node.js 'os' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/globals.js (42)
Object.apply
webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/globals.js (42:19)
eval
webpack-internal:///(middleware)/./node_modules/firebase-admin/lib/app/credential-internal.js (38:20)
eval
webpack-internal:///(middleware)/./node_modules/firebase-admin/lib/app/credential-internal.js (44:3)
Object.(middleware)/./node_modules/firebase-admin/lib/app/credential-internal.js
file:/C:/x/x/.next/server/src/middleware.js (1708:1)

I have a firebase-admin.ts file:

import * as admin from 'firebase-admin';

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert(JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT as string)),
  });
}

const firestore = admin.firestore();
const auth = admin.auth();

export { firestore, auth };

I use auth inside the middleware to authenticate every api request. It looks like I can't use firebase-admin lib because it uses the os module.


Solution

  • It is expected that code that depends on native nodejs APIs will not work on Edge Runtime. That product is based on web APIs only. You can see what is and is not supported in their documentation. Specifically under unsupported APIs:

    Native Node.js APIs are not supported. For example, you can't read or write to the filesystem.

    Firebase Admin was designed to work on pure nodejs runtimes, or runtimes that intend to be compatible with nodejs (such as Bun).