Code for a browser Response Cookies

Here is an example code for setting and getting response cookies using JavaScript:

Setting a response cookie:

// Set a cookie that expires in 7 days
document.cookie = "name=value; expires=" + new Date( + 604800000).toUTCString() + "; path=/";

This code sets a cookie with the name "name" and value "value", with an expiration time of 7 days from the current time. The path attribute is set to "/" to ensure the cookie is available to all pages on the website.

Getting a response cookie:

function getCookie(name) {
  const cookieString = document.cookie;
  const cookieArray = cookieString.split(';');
  for (let i = 0; i < cookieArray.length; i++) {
    const cookie = cookieArray[i].trim();
    if (cookie.startsWith(name + '=')) {
      return cookie.substring(name.length + 1, cookie.length);
  return null;

// Example usage
const myCookie = getCookie('name');
if (myCookie) {
  console.log('Cookie value:', myCookie);
} else {
  console.log('Cookie not found');

This code defines a function getCookie that takes a cookie name as an argument and returns the value of the cookie, or null if the cookie is not found. The function splits the document.cookie string into an array of individual cookies, then loops through each cookie to find the one with the specified name. If found, the function returns the cookie value. Otherwise, it returns null.

Note that response cookies are set by the server in the HTTP response headers, and can be retrieved by the client as shown above. The specific method for setting response cookies may vary depending on the server-side technology being used.

Related Articles

- All From ChatGPT