Read Value of Browser Cookie in JavaScript

- 1 minute read

The following JavaScript function will return the value of a cookie set in the browser:

const getCookie = (key) => {
    return `; ${document.cookie}`.split(`; ${key}=`).pop().split(`;`).shift();
};

This getCookie function accepts a string value called key. If there is a cookie set in the browser with a matching key, then the string value of that cookie will be returned.

If there is not a cookie set with a matching key, then an empty string will be returned.

This one-liner variant of the getCookie function has the exact same behavior as the previous implementation:

const getCookie = (key) => return `; ${document.cookie}`.split(`; ${key}=`).pop().split(`;`).shift();

Link to this section Conclusion

I’ve found this short snippet to be tremendously useful, and I’m actually surprised that it hasn’t yet been implemented as a built-in function.

Anyway, I hope you found it useful too!