John
John

Reputation: 9456

__filename missing 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);
    
  2. 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?

Upvotes: 0

Views: 18

Answers (0)

Related Questions