Skip to content

Instantly share code, notes, and snippets.

@pronazmul
Last active March 28, 2022 10:03
Show Gist options
  • Save pronazmul/a569616f8c38a1b95655101db0ceece5 to your computer and use it in GitHub Desktop.
Save pronazmul/a569616f8c38a1b95655101db0ceece5 to your computer and use it in GitHub Desktop.
JavaScript Cookies

JavaScript Cookies

Create a Cookie:

  • JavaScript can create, read, and delete cookies with the document.cookie property.
  • Without Expire Time Browser will forget Cookie after reload or close browser. You can also add an expiry date (in UTC time).
  • If set path to root path=/ will be available everywhere inside application. By default, the cookie belongs to the root.
  • If set path to specific URL like path=/about will be available only inside that url.

Default Way:

	document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Using Function:

	/**
	 * @description - Function Helps to Set Cookie.
	 * @param {String}  Key of Cookie.
	 * @param {String}  Value of Cookie.
	 * @param {Number}  Days of Duration of Cookie. Default `1` Day
	 * @param {String}  Path of Cookie. Default `path=/`
	 * @returns {Object}  Created Cookie In Object Format.
	 */
	export const setCookie = (key, value, days = 1, path = '/') => {
	  // Make Cookie String
	  const cookieString = `${key}=${value};expires=${new Date(
	    new Date().getTime() + days * 24 * 60 * 60 * 1000
	  ).toUTCString()};path=${path}`;

	  // Create Cookie
	  document.cookie = cookieString;

	  // Create Object From Cookie
	  const cookieObject = document.cookie
	    .split(';')
	    .map((v) => v.trim().split('='))
	    .reduce((state, [k, v]) => ({ ...state, [k]: v }), {});
	  return cookieObject;
	};

Get a Cookie Values:

  • document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

Default Way:

	document.cookie 

Using Function:

	/**
	 * @description - This Function helps Get Single or multiple Cookie Values.
	 * @param {String}  Key of Cookie. Default Nothing.
	 * @returns {String || Object}  If Key provide Return Valu of that key otherwise full Object.
	 */
	export const getCookie = (key = false) => {
	  // Make Cookie String To Object
	  const cookieObject = document.cookie
	    .split(';')
	    .map((v) => v.trim().split('='))
	    .reduce((state, [k, v]) => ({ ...state, [k]: v }), {});
	  return key ? cookieObject[key] : cookieObject;
	};

Check a Cookie Value:

  • No method available by default to check cookie Value is available or not.

Using Function:

	/**
	 * @description - This Function helps Check Cookie Value Available or Not.
	 * @param {String}  Key of Cookie.
	 * @returns {Boolean}  Boolean value cookie exists or not.
	 */
	export const checkCookie = (key) => {
	  // Make Cookie String To Object
	  const cookieObject = document.cookie
	    .split(';')
	    .map((v) => v.trim().split('='))
	    .reduce((state, [k, v]) => ({ ...state, [k]: v }), {});
	  return key ? (cookieObject[key] ? true : false) : false;
	};

Change or modify a Cookie:

  • With JavaScript, you can change a cookie the same way as you create it.
  • The old cookie is overwritten.

Default Way:

	document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Using Function:

	/**
	 * @description - Function Helps to Set Cookie.
	 * @param {String}  Key of Cookie.
	 * @param {String}  Value of Cookie.
	 * @param {Number}  Days of Duration of Cookie. Default `1` Day
	 * @param {String}  Path of Cookie. Default `path=/`
	 * @returns {Object}  Created Cookie In Object Format.
	 */
	export const setCookie = (key, value, days = 1, path = '/') => {
	  // Make Cookie String
	  const cookieString = `${key}=${value};expires=${new Date(
	    new Date().getTime() + days * 24 * 60 * 60 * 1000
	  ).toUTCString()};path=${path}`;

	  // Create Cookie
	  document.cookie = cookieString;

	  // Create Object From Cookie
	  const cookieObject = document.cookie
	    .split(';')
	    .map((v) => v.trim().split('='))
	    .reduce((state, [k, v]) => ({ ...state, [k]: v }), {});
	  return cookieObject;
	};

Delete a Cookie:

  • Deleting a cookie is very simple.
  • You don't have to specify a cookie value when you delete a cookie.
  • Just set the expires parameter to a past date.

Default Way:

	document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Using Function:

	/**
	 * @description - Function Helps to Remove Cookie.
	 * @param {String}  Key of Removed Item of Cookie.
	 * @param {String}  Path of Removed Cookie. Default `path=/`
	 * @returns {Object}  Exists Available Cookie As Object.
	 */
	export const removeCookie = (key, path = '/') => {
	  // Make Removed Cookie String
	  const cookieString = `${key}=;expires=${new Date(
	    0
	  ).toUTCString()};path=${path}`;

	  // Set Emptied Cookie on Previous Date
	  document.cookie = cookieString;

	  // Create Object From Cookie
	  const cookieObject = document.cookie
	    .split(';')
	    .map((v) => v.trim().split('='))
	    .reduce((state, [k, v]) => ({ ...state, [k]: v }), {});
	  return cookieObject;
	};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment