Skip to content

Instantly share code, notes, and snippets.

@tejas-hosamani
Last active July 29, 2020 07:14
Show Gist options
  • Save tejas-hosamani/ee9400ea2c59aa4793d37dac0a7136f3 to your computer and use it in GitHub Desktop.
Save tejas-hosamani/ee9400ea2c59aa4793d37dac0a7136f3 to your computer and use it in GitHub Desktop.
// Usage: getCookie('cookie-name', ctx.req.headers.cookie)
export function getCookie(cname, cookieSourceString = "") {
if (typeof window !== "undefined") {
// eslint-disable-next-line no-param-reassign
cookieSourceString = document.cookie;
}
const name = cname + "=";
const decodedCookie = decodeURIComponent(cookieSourceString);
const 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 "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment