denoland/deno · error · TypeError

Method is not valid

Error message

Method is not valid

What it means

validateAndNormalizeMethod runs the method against the HTTP token regex (HTTP_TOKEN_CODE_POINT_RE, per RFC 7230 tchar). If any character is not a valid token code point — spaces, non-ASCII, control chars, delimiters like '(', ')' — it throws TypeError 'Method is not valid'. This runs for every Request constructor and fetch() method option.

Source

Thrown at ext/fetch/23_request.js:273

  "get": "GET",
  "HEAD": "HEAD",
  "head": "HEAD",
  "OPTIONS": "OPTIONS",
  "options": "OPTIONS",
  "PATCH": "PATCH",
  "POST": "POST",
  "post": "POST",
  "PUT": "PUT",
  "put": "PUT",
};

/**
 * @param {string} m
 * @returns {string}
 */
function validateAndNormalizeMethod(m) {
  if (RegExpPrototypeExec(HTTP_TOKEN_CODE_POINT_RE, m) === null) {
    throw new TypeError("Method is not valid");
  }
  const upperCase = StringPrototypeToUpperCase(m);
  switch (upperCase) {
    case "DELETE":
    case "GET":
    case "HEAD":
    case "OPTIONS":
    case "POST":
    case "PUT":
      return upperCase;
    case "CONNECT":
    case "TRACE":
    case "TRACK":
      throw new TypeError("Method is forbidden");
  }
  return m;
}

View on GitHub (pinned to 89f33cbef2)

Solutions

  1. Trim and validate the method against ^[!#$%&'*+.^_`|~0-9A-Za-z-]+$ before using it
  2. If the value comes from user input, reject non-token methods with a 400 rather than letting the TypeError escape
  3. Hardcode known-good literals ('GET', 'POST', ...) at call sites

Example fix

// before
const method = userMethod; // e.g. 'POST '\nawait fetch(url, { method });

// after
const TOKEN_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
const method = userMethod.trim();
if (!TOKEN_RE.test(method)) throw new Error(`invalid method: ${JSON.stringify(method)}`);
await fetch(url, { method });
Defensive patterns

Strategy: type-guard

Validate before calling

const HTTP_METHOD_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
function normalizeMethod(m) {
  const s = String(m).trim();
  if (!HTTP_METHOD_RE.test(s)) {
    throw new Error(`invalid HTTP method: ${JSON.stringify(s)}`);
  }
  return s.toUpperCase();
}

Type guard

/** @param {unknown} m */
function isValidHttpMethod(m) {
  return typeof m === 'string' && /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(m);
}

Prevention

When it happens

Trigger: new Request(url, { method: 'POST ' }) (trailing space), fetch(url, { method: 'größe' }) (non-ASCII), method containing CR/LF or characters like '"' or '{}'.

Common situations: Methods built from unvalidated user input (custom X-HTTP-Method-Override headers), trailing whitespace from config files/env vars, or concatenated strings that accidentally include a newline.

Related errors


AI-assisted analysis of denoland/deno@89f33cbef2 (2026-08-16). Data as JSON: /api/errors/f635d40c630b3352. Report an issue: GitHub.