Extracts a CSRF token from an HTML string.
The full HTML document as a string. Must be a complete or partial HTML response.
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:
<input name="_token" value="TOKEN"> (order of attributes may vary)<meta name="csrf-token" content="TOKEN"> (order may vary)Regular expressions are case‑insensitive and handle single or double quotes.
Edge cases:
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.
Extracts a CSRF token from an HTML string.
Remarks
Searches for
<input name="_token" value="...">or<meta name="csrf-token" content="...">patterns.Param: html
The full HTML document as a string.
Returns
The extracted token, or
nullif not found.See
extractCsrfToken
Since
0.1.1