CSRF-X Auth Library - v1.0.3
    Preparing search index...

    Function extractCsrfToken

    Extracts a CSRF token from an HTML string.

    Searches for <input name="_token" value="..."> or
    <meta name="csrf-token" content="..."> patterns.

    The full HTML document as a string.

    The extracted token, or null if not found.

    0.1.1

    • Extracts a CSRF token from an HTML string.

      Parameters

      • html: string

        The full HTML document as a string. Must be a complete or partial HTML response.

      Returns string | null

      The extracted token string, or null if no token is found in any of the supported patterns.

      The function searches for the token in the following order:

      1. <input name="_token" value="TOKEN"> (order of attributes may vary)
      2. <meta name="csrf-token" content="TOKEN"> (order may vary)

      Regular expressions are case‑insensitive and handle single or double quotes.

      Edge cases:

      • If the HTML contains multiple matching tokens, the first one encountered is returned.
      • The token value is trimmed of leading/trailing whitespace.
      • Malformed HTML or missing quotes may cause extraction to fail; consider using a proper HTML parser for production if the patterns are unreliable.

      Performance: The function uses regular expressions that scan the entire HTML string.
      For very large HTML documents (e.g., >1 MB), consider extracting the token from a smaller fragment.

      // Input tag pattern
      const html = `<form><input type="hidden" name="_token" value="abc123"></form>`;
      const token = extractCsrfToken(html);
      console.log(token); // "abc123"
      // Meta tag pattern
      const metaHtml = `<meta name="csrf-token" content="xyz789">`;
      extractCsrfToken(metaHtml); // "xyz789"
      // Attribute order variation
      const altHtml = `<input value="def456" name="_token">`;
      extractCsrfToken(altHtml); // "def456"

      AuthClient - Uses this function during login flow.

      0.1.1