JS - Get csrf-token from browser cookies

A simple .js script to retrieve the csrf cookie from the browser. Prerequisite for any js requests that require X-CSRFToken header

API: /api/v1/cheatsheet/js-get-csrf-token-from-browser-cookies

JavaScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function getCSRFToken() {
    let cookie_array = document.cookie.split(';');
    let token = null;

    for (let x in cookie_array) {
        if (cookie_array[x].includes('csrf')) {
            token = cookie_array[x].split('=')[1];
        };
    };

    return token;
}

Join the Newsletter

Practical insights on Django, backend systems, deployment, architecture, and real-world development — delivered without noise.

Get updates when new guides, learning paths, cheat sheets, and field notes are published.

No spam. Unsubscribe anytime.



There is no third-party involved so don't worry - we won't share your details with anyone.