Mastering Cookies in JavaScript: Essential Guide for Frontend Developer Interviews

Cookies are an essential part of web development, allowing developers to store small amounts of data directly in the user's browser. They are often used for session management, personalization, and tracking. Understanding how to work with cookies in JavaScript is a fundamental skill that can give you an edge in interviews. In this blog post, we’ll dive into cookies, how to create, read, and delete them using JavaScript, and discuss common interview questions related to cookies.
What Are Cookies?
Cookies are small text files stored on the client side (i.e., in the user's browser) that hold data. The server can access this data on subsequent requests, making cookies a useful tool for maintaining state in stateless protocols like HTTP.
Key Characteristics:
Size Limit: Typically, cookies are limited to about 4KB.
Expiration: Cookies can be set to expire at a specific date or after a certain amount of time.
Scope: Cookies have a scope that can be set to specific paths and domains.
Security: Cookies can be made secure and accessible only over HTTPS.
Creating Cookies in JavaScript
Creating cookies in JavaScript is straightforward using the document.cookie property. To set a cookie, you assign a string to document.cookie that follows the format:
codedocument.cookie = "key=value; expires=date; path=/";
Example:
// Set a cookie with a key "username" and value "JohnDoe"
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
Key Points:
expires: Sets the expiration date. If omitted, the cookie will be a session cookie and will expire when the browser is closed.path: Defines the URL path that must exist in the requested URL for the browser to send the cookie header. By default, it’s the current page.
Reading Cookies in JavaScript
To read cookies, you can access document.cookie. This property returns all cookies as a single string, with each cookie separated by a semicolon.
Example:
// Get all cookies
let allCookies = document.cookie;
console.log(allCookies); // e.g., "username=JohnDoe; theme=dark"
// Parse a specific cookie value
function getCookieValue(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
let username = getCookieValue('username');
console.log(username); // "JohnDoe"
Key Points:
Cookies are stored as a single string and need to be parsed to access individual values.
You may use
decodeURIComponent()to decode the cookie value, especially if it contains special characters.
Deleting Cookies in JavaScript
To delete a cookie, you can set its expiration date to a past date.
Example:
// Delete the "username" cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
Key Points:
- Ensure the
pathmatches the one used when the cookie was created, or the cookie might not be deleted.
Interview Questions on Cookies
Understanding how to work with cookies is crucial, but so is knowing the common questions that might come up in an interview:
What are the differences between session cookies and persistent cookies?
Session Cookies: temporary and deleted when the browser is closed.
Persistent Cookies: Have an expiration date and remain stored until that date is reached.
How can you make cookies secure?
Use the
Secureflag to ensure the cookie is sent only over HTTPS.Use the
HttpOnlyflag to prevent client-side scripts from accessing the cookie.
What are some common issues with cookies?
Size Limit: Exceeding the 4KB limit can cause issues.
Security Risks: If not secured properly, cookies can be intercepted (e.g., XSS attacks).
Third-Party Cookies: These are often blocked or restricted by browsers due to privacy concerns.
How do you handle cookies with different domains or paths?
- Use the
DomainandPathattributes to control the scope of cookies.
- Use the
Explain the SameSite cookie attribute and its importance.
- The
SameSiteattribute helps protect against cross-site request forgery (CSRF) attacks by controlling when cookies are sent along with requests initiated by third-party websites.
- The
Conclusion
Cookies are a powerful tool in web development, and understanding how to manipulate them in JavaScript is a key skill for any frontend developer. Whether you’re setting, reading, or deleting cookies, knowing the ins and outs will help you not only in coding but also in acing those interview questions. Practice working with cookies, and you'll be well-prepared to handle any cookie-related question that comes your way in an interview.




