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:
- Root Object Resolution (
_root.js): Lodash determines the global context by checkingfreeGlobal(Node.jsglobal),window,self, andFunction('return this')(). In a browser, this resolves towindoworself. - CommonJS Environment Detection: Lodash inspects the
variables
exportsandmodule. If running in a true CommonJS module context, it checks ifmodule.exports === exports. - Reference Acquisition: If the context permits,
Lodash attempts to extract
Bufferviaroot.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:
- Nullish Check: It verifies that the input argument
is not
nullorundefined. - Boolean Flag Check (
_isBuffer): The polyfill explicitly checksBoolean(value && value._isBuffer). All instances created by thebufferpackage define this property, avoidinginstanceofissues across different execution realms or iframes. - Duck-Typing Constructor Fallback: To maintain
interoperability with other buffer implementations or native arrays, the
polyfill checks:
value.constructor != nulltypeof 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.