DEV Community

Cover image for Some useful custom utilityđź›  functions for cookie handling in javascript
Rajesh Royal
Rajesh Royal

Posted on

Some useful custom utilityđź›  functions for cookie handling in javascript

For a simple cookie operation I prefer to have my own custom functions(obviously from google) instead of using a cookie library in React.js

1. setCookie

// setCookie("cookiename", cookieExist, COOKIE_EXPIRY_TIME);
// example - setCookie("username", cookieExist, (0.5 * 60 * 1000)); this cookie expires in 30 seconds.
// the cookie expiry time have to be in seconds so convert your time in seconds and after that pass it.

export function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + exdays);
    let expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
Enter fullscreen mode Exit fullscreen mode

2. getCookie

// get a cookie and Its value
export function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
Enter fullscreen mode Exit fullscreen mode

3. checkCookie

// pass the name of the cookie as string which you want to check that if It exists or not.
export function checkCookie(cookiename) {
    let cookieExist = getCookie(cookiename);
    if (cookieExist != "") {
        return cookieExist;
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

How you find it useful 🙂🙂

Top comments (0)