DEV Community

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

Posted on

5 1

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 🙂🙂

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay