Skip to content

Instantly share code, notes, and snippets.

@davidalekna
Last active January 9, 2020 10:54
Show Gist options
  • Save davidalekna/bd32e0bb0221f0821bce4e47ab82e29f to your computer and use it in GitHub Desktop.
Save davidalekna/bd32e0bb0221f0821bce4e47ab82e29f to your computer and use it in GitHub Desktop.
client cookies get, set and delete
const setCookie = (
name: string,
value: string,
days: number = 7,
path: string = "/"
): void => {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
const cookie = `${name}=${encodeURIComponent(
value
)}; expires=${expires}; path=${path}`;
document.cookie = cookie;
};
// setCookie('tasty_cookie', 'strawberry')
const getCookie = (name: string): string | void => {
return document.cookie?.split(";").reduce((acc, cookie) => {
const [key, value] = cookie.trim().split("=");
return { ...acc, [key]: decodeURIComponent(value) };
}, {})[name];
};
// getCookie('tasty_cookie'): 'strawberry'
const deleteCookie = (name: string, path?: string): void => {
setCookie(name, "", -1, path);
};
// deleteCookie('tasty_cookie')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment