{
    "slug": "js_csrf_fetch",
    "term": "CSRF Token Handling in Fetch & Axios",
    "category": "javascript",
    "difficulty": "intermediate",
    "short": "Including PHP-generated CSRF tokens in JavaScript requests — reading from meta tags or cookies and attaching to every state-changing request.",
    "long": "PHP generates a CSRF token per session (Laravel, Symfony). JavaScript must include it on POST/PUT/PATCH/DELETE. Two patterns: meta tag (Laravel: <meta name='csrf-token' content='{{ csrf_token() }}'>) read via querySelector; cookie (XSRF-TOKEN) read via document.cookie or axios which reads it automatically (same-origin). SPA with separate PHP API: include token in initial page data (window.__csrf), API responses (custom header), or refresh endpoint.",
    "aliases": [
        "CSRF token JS",
        "X-CSRF-Token",
        "XSRF-TOKEN",
        "Laravel CSRF JavaScript"
    ],
    "tags": [
        "javascript",
        "security",
        "php-integration"
    ],
    "misconception": "SameSite=Lax cookies make CSRF tokens unnecessary for all JavaScript requests — SameSite=Lax only blocks cross-site form submissions and some navigation; programmatic fetch() from the same origin still needs CSRF tokens if using cookie auth.",
    "why_it_matters": "Every state-changing AJAX request to PHP must include the CSRF token — omitting it causes Laravel/Symfony to return 419 Token Mismatch or 403 errors.",
    "common_mistakes": [
        "Not refreshing the CSRF token after session expiry",
        "Missing CSRF token on multipart fetch (FormData) requests",
        "Hardcoding the token instead of reading it dynamically from meta tag"
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "csrf",
        "js_fetch_api",
        "js_axios_patterns",
        "js_form_data_api"
    ],
    "prerequisites": [
        "csrf",
        "js_fetch_api"
    ],
    "refs": [
        "https://laravel.com/docs/csrf#csrf-x-csrf-token"
    ],
    "bad_code": "// No CSRF token — Laravel returns 419:\nfetch('/api/order', { method: 'POST', body: JSON.stringify(order) });",
    "good_code": "// Read from meta tag (Laravel/Symfony pattern):\nconst csrf = document.querySelector('meta[name=csrf-token]')?.content;\n\n// Attach to all state-changing requests:\nasync function post(url, data) {\n    return fetch(url, {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n            'X-CSRF-Token': csrf,\n        },\n        body: JSON.stringify(data),\n    });\n}\n\n// Axios reads XSRF-TOKEN cookie automatically for same-origin:\n// axios.defaults.xsrfCookieName = 'XSRF-TOKEN';\n// axios.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';",
    "quick_fix": "Read the CSRF token from <meta name='csrf-token'> and include as X-CSRF-Token header on all POST/PUT/PATCH/DELETE fetch requests",
    "severity": "high",
    "effort": "low",
    "created": "2026-03-17",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/js_csrf_fetch",
        "html_url": "https://codeclaritylab.com/glossary/js_csrf_fetch",
        "json_url": "https://codeclaritylab.com/glossary/js_csrf_fetch.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[CSRF Token Handling in Fetch & Axios](https://codeclaritylab.com/glossary/js_csrf_fetch) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/js_csrf_fetch"
            }
        }
    }
}