cheeriojs/cheerio · error · Error

cheerio.load() expects a string

Error message

cheerio.load() expects a string

What it means

cheerio.load() accepts a string, node, array of nodes, or Buffer — but not null or undefined. A null/undefined content argument (loosely checked with == null) fails fast with this error instead of crashing deeper in the parser.

Source

Thrown at src/load.ts:142

   * markup.
   *
   * Note that similar to web browser contexts, this operation may introduce
   * `<html>`, `<head>`, and `<body>` elements; set `isDocument` to `false` to
   * switch to fragment mode and disable this.
   *
   * @param content - Markup to be loaded.
   * @param options - Options for the created instance.
   * @param isDocument - Allows parser to be switched to fragment mode.
   * @returns The loaded document.
   * @see {@link https://cheerio.js.org/docs/basics/loading#load} for additional usage information.
   */
  return function load(
    content: string | AnyNode | AnyNode[] | Buffer,
    options?: CheerioOptions | null,
    isDocument = true,
  ): CheerioAPI {
    if ((content as string | null) == null) {
      throw new Error('cheerio.load() expects a string');
    }

    const internalOpts = flattenOptions(options);
    const initialRoot = parse(content, internalOpts, isDocument, null);

    /**
     * Create an extended class here, so that extensions only live on one
     * instance.
     */
    class LoadedCheerio<T> extends Cheerio<T> {
      _make<T>(
        selector?: ArrayLike<T> | T | string,
        context?: BasicAcceptedElems<AnyNode> | null,
      ): Cheerio<T> {
        const cheerio = initialize(selector, context);
        cheerio.prevObject = this;

        return cheerio;

View on GitHub (pinned to a1be131f9b)

Solutions

  1. Default the content: cheerio.load(html ?? '') or guard with if (!html) return
  2. Trace where the variable comes from (file read, HTTP call) and fix that upstream failure
  3. Add explicit checks after async fetches/reads before calling load

Example fix

// before
const $ = cheerio.load(await getFileContents(path)); // may be undefined
// after
const html = await getFileContents(path);
if (html == null) throw new Error(`No content at ${path}`);
const $ = cheerio.load(html);
Defensive patterns

Strategy: validation

Validate before calling

if (content == null) throw new Error('Cannot load empty document');
const $ = cheerio.load(content);

Type guard

const isLoadable = (c: unknown): c is string | Buffer | object =>
  c != null && (typeof c === 'string' || Buffer.isBuffer(c) || typeof c === 'object');

Try / catch

// Prefer pre-validation; if wrapping:
try { const $ = cheerio.load(content); } catch (e) { if (e instanceof Error && /cheerio\.load\(\) expects a string/.test(e.message)) return cheerio.load(''); else throw e; }

Prevention

When it happens

Trigger: Calling cheerio.load(null), cheerio.load(undefined), or load(someVar) where someVar is undefined — e.g. a missing file read, a failed fetch body, an absent request field.

Common situations: Loading a file that doesn't exist (fs.readFileSync on wrong path returning undefined in wrappers), reading req.body before body-parsing middleware, awaiting a fetch that returned undefined in a mocked test, race conditions where data isn't fetched yet.

Related errors


AI-assisted analysis of cheeriojs/cheerio@a1be131f9b (2026-08-28). Data as JSON: /api/errors/9ee5588e17ae353f. Report an issue: GitHub.