Question

Node script works with `node file.js` but fails on Vercel with 'require is not defined'

Solved · 359 viewsasked by tomvibes

The Vercel logs:

Bolt generated the utility with require. Locally fine.

What I’ve tried

Renamed to .cjs, then imports elsewhere broke.

Comment

2 answers

Marked as helpful by the asker
jonas_k

Your package.json has "type": "module", so every .js file is ESM and require does not exist there. Pick one world and stay in it. For a modern project: ESM.

// before
const fs = require('fs');
// after
import fs from 'node:fs';

Tell Bolt: "this project is ESM, use import/export only". It remembers within a session.

Comment
Converted the three utils to import. Export works on Vercel now. tomvibes
thandeka

If one old dependency really only works with require, you don't have to leave ESM for it:

import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const legacy = require('some-old-lib');

And watch for __dirname next, it doesn't exist in ESM either. import.meta.dirname works on Node 20.11+.

Comment