`__filename` missing error in a Nuxt 3 project on Vercel?

I’m working on a Nuxt 3 project that is fully based on ECMAScript modules and is deployed on Vercel. Some dependencies (or their compiled code) expect CommonJS globals like __filename, but in an ESM environment these are not defined. Initially, I encountered an error with __dirname and managed to work around it by using both a server-only plugin and a Vite define replacement in my nuxt.config.js. However, I’m now facing the following runtime error:

ReferenceError: __filename is not defined
    at pm (file:///var/task/chunks/routes/api/submit-lead.mjs:183:1110)
    ...

What I’ve Tried

  1. Global Polyfill via a Server-Only Plugin:
    I created a plugin (plugins/global-polyfill.server.js) with:
import { fileURLToPath } from 'url';
import { dirname } from 'path';

globalThis.__dirname = dirname(fileURLToPath(import.meta.url));
globalThis.__filename = fileURLToPath(import.meta.url);
  1. Vite Define Replacement in nuxt.config.js:
    I also added:
import { fileURLToPath } from 'url';

export default defineNuxtConfig({
  vite: {
    define: {
      __dirname: JSON.stringify(process.cwd()),
      __filename: JSON.stringify(fileURLToPath(import.meta.url))
    }
  }
});

While these approaches seemed to resolve the __dirname issue, the __filename error persists.

How can I properly provide or replace __filename in my Nuxt 3 ESM project deployed on Vercel so that dependencies expecting CommonJS globals work correctly?

Any insights or recommended approaches to handle this CJS/ESM discrepancy would be greatly appreciated.

Hi, @john-hashbangio! Welcome to the Vercel Community :wave:

Thanks for your patience! Did you manage to find a solution here? If not, can you create a minimal reproducible example for us so that we can dig deeper?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.