Many npm packages rely on Node.js-specific features like Buffer, fs, or net.Socket, making them unusable in environments like Vercel Edge Functions, Cloudflare Workers, or browsers. Using esbuild as a bundler, several techniques can solve this: installing third-party shim packages for imported or global objects, using esbuild's --inject flag to polyfill globals like Buffer, creating stub packages for non-critical Node built-ins like fs, reimplementing simple Node APIs using Web APIs (e.g., TextDecoder for StringDecoder), and package masquerading to swap one package for another in a dependency tree. These approaches are illustrated with real examples from building the @neondatabase/serverless Postgres driver, which adapts the node-postgres pg package for serverless environments.

7m read timeFrom neon.com
Post cover image
Table of contents
Third-party shims: imported objectsThird-party shims: global objectsRoll your own shims: global objectsRoll-your-own shims: stub packagesRoll-your-own shims: simple packagesRoll-your-own shims: complex packagesPackage masquerading