SoFunction
Updated on 2025-04-13

Two ways to use cookies in front-end are explained in detail

Preface

In front-end development, cookies are a commonly used client storage mechanism, which allows the server to store a small amount of data on the client and read this data in subsequent requests. Cookies are mainly used to maintain user session status, personalize settings, track user behavior, etc. There are two main ways to use cookies in front-end: automatic management through the browser (implicit use) and explicit operations through JavaScript. These two methods will be explained in detail below.

1. Automatic management through the browser (implicit use)

In this way, developers do not need to operate cookies directly, but rely on the browser to automatically add and manage cookies in HTTP requests and responses.

1. Server settings cookies

The server responds to the HTTP headerSet-CookieFields to set cookies. For example, a typical HTTP response header might contain the following directives that set cookies:

Set-Cookie: sessionid=abc123; Path=/; Secure; HttpOnly

here,sessionidIt is the name of the cookie.abc123It is its value.PathSpecifies the path to function of the cookie.SecureIndicates that cookies are only sent in HTTPS requests.HttpOnlyIt means that cookies can only be accessed through the HTTP protocol, not through JavaScript, thereby increasing security.

2. Browser storage and sending cookies

Once the server has set a cookie, the browser stores the cookie on the user's computer and automatically includes the cookie when subsequent requests are sent to the same domain (or subdomain). For example, when a user visits the site again, the browser includes the following fields in the HTTP request header:

Cookie: sessionid=abc123

In this way, the server can recognize the user's session status by reading this cookie.

2. Explicit operation through JavaScript

Although browsers automatically manage most cookies, sometimes developers need to explicitly read, modify, or delete cookies through JavaScript. This is usually used in scenarios where cookie data needs to be processed dynamically on the client side.

1. Read Cookies

JavaScript cannot be accessed directly withHttpOnlyCookies with attributes, but for other cookies, they can be passedAttributes are read. It should be noted thatReturns a string containing all cookies, separated by semicolons and spaces, as shown in:

"sessionid=abc123; userid=xyz789"

To read a specific cookie, the string needs to be parsed manually. For example:

function getCookie(name) {
    let matches = (new RegExp(
        "(?:^|; )" + (/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
}

let sessionid = getCookie('sessionid');
(sessionid); // Output: abc123

2. Set cookies

Setting cookies through JavaScript is usually done by directly modifyingAttributes are implemented. For example:

 = "userid=xyz789; Path=/; Secure; Expires=Wed, 09 Jun 2021 10:18:14 GMT";

here,useridIt is the name of the cookie.xyz789It is its value.PathSpecifies the path to function of the cookie.SecureIt means that it is sent only via HTTPS.ExpiresSet the expiration time of the cookie. If not setExpiresorMax-Age, the cookie becomes a session cookie and is automatically deleted when the browser is closed.

3. Delete Cookies

The way to delete a cookie is to set the expiration time of the cookie to a past date. For example:

 = "userid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT";

Here, byuseridThe value of the cookie is set to an empty string and its expiration time is set to a distant past, and the browser will delete the cookie.

Attachment: The function of adding, deleting, modifying and checking that encapsulates your own cookie

/*
	 2017/02/20
	 Cookie operation
  */
function setCookie(key, value, iDay) {
	var oDate = new Date();
	(() + iDay);
	 = key + '=' + value + ';expires=' + oDate;

}
function removeCookie(key) {
	setCookie(key, '', -1);//Here you only need to return the shelf life of the cookie to delete it by one day}
function getCookie(key) {
	var cookieArr = ('; ');
	for(var i = 0; i < ; i++) {
		var arr = cookieArr[i].split('=');
		if(arr[0] === key) {
			return arr[1];
		}
	}
	return false;
}

Summarize

The two ways of using cookies on the front end have their own advantages and disadvantages. Automatically manage cookies through browsers, developers do not need to write additional code, but rely on the correct configuration of the server. Through JavaScript explicit operation of cookies, developers can more flexibly control the read, write and delete cookies, but they need to manually handle string parsing and setting, and need to pay attention to security issues (such as avoiding cross-site scripting attacks). In actual development, appropriate methods should be selected based on specific needs and best practices should be followed to ensure the security and privacy of cookies.

This is the end of this article about the two ways to use cookies on the front-end. For more related content on the front-end cookies, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!