How Lodash isBuffer Checks Work in Webpack

When using the Lodash _.isBuffer method in a Webpack-bundled client-side application, the runtime behavior depends directly on how the bundle resolves Node.js environment globals. This article breaks down how Lodash detects the presence of the Buffer API in the browser, the specific internal checks evaluated by Lodash's internal helpers, and how bundled polyfills such as Feross Aboukhadijeh's buffer package respond to _.isBuffer calls.

Lodash's Root Environment Inspection

Before testing any variable, Lodash evaluates its environment through internal utility modules to determine whether Node.js globals are accessible:

  1. Root Object Resolution (_root.js): Lodash determines the global context by checking freeGlobal (Node.js global), window, self, and Function('return this')(). In a browser, this resolves to window or self.
  2. CommonJS Environment Detection: Lodash inspects the variables exports and module. If running in a true CommonJS module context, it checks if module.exports === exports.
  3. Reference Acquisition: If the context permits, Lodash attempts to extract Buffer via root.Buffer.

If root.Buffer does not exist—which is standard in modern browser environments bundled with Webpack 5 without explicit polyfills—Lodash immediately falls back to stubFalse, a utility function that always returns false.

Webpack Polyfill Injection

In Webpack 4 (which bundled Node.js core polyfills automatically) or Webpack 5 (configured with resolve.fallback: { buffer: require.resolve('buffer/') } and a ProvidePlugin for Buffer), the global Buffer object points to the buffer npm package.

Under this setup, root.Buffer successfully resolves to the polyfilled Buffer class, and Lodash assigns:

var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
var isBuffer = nativeIsBuffer || stubFalse;

Checks Executed by the Polyfill

When _.isBuffer(value) executes and delegates to the polyfill's Buffer.isBuffer, the following internal checks are performed:

  1. Nullish Check: It verifies that the input argument is not null or undefined.
  2. Boolean Flag Check (_isBuffer): The polyfill explicitly checks Boolean(value && value._isBuffer). All instances created by the buffer package define this property, avoiding instanceof issues across different execution realms or iframes.
  3. Duck-Typing Constructor Fallback: To maintain interoperability with other buffer implementations or native arrays, the polyfill checks:
    • value.constructor != null
    • typeof value.constructor.isBuffer === 'function'
    • value.constructor.isBuffer(value)

If any of these conditions confirm the object is an instance of a Node.js-compatible buffer, the method returns true. Otherwise, or if no polyfill is bundled into the Webpack output, the check resolves safely to false.