Cookie Types
Cookies are small pieces of data stored on users' devices that can be used to track their browsing habits, preferences, and behavior. There are several types of cookies, including:
To set cookies in your web application, you'll need to create a JavaScript file (usually called a 'cookie.js' or similar) and include the following code:
function setCookie(key, value, expires) { var date = new Date(); if (expires == "days") { date.setDate(date.getDate() + expires); } else if (expires == "hours") { date.setHours(expires); } // Set the cookie document.cookie = key + "=" + escape(value) + ";expires=" + expires; } function getCookie(key) { var value = ""; var cookies = document.cookie.split('; '); for (var i in cookies) { if (cookies[i].indexOf(key) == 0) return cookies[i].substr(key.length + 1); } return false; }
When a user navigates to your web application, their browser sends an HTTP request. Cookies are sent along with the request, but they're not stored on the server-side by default. However, some cookies can be included in the response headers as well.
To include a cookie in the response header, you'll need to set an HTTP header (usually called 'Set-Cookie') and include the desired value for the cookie name and value. For example:
responseHeader = "Set-Cookie: cookie_name=cookie_value; httpOnly=True"
Here are a few best practices and tricks to keep in mind when working with cookies: