Skip to content

Cookies

This lesson explains Cookies with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Cookies API Overview

Cookies are small pieces of data stored by the browser and sent to the server with every HTTP request for the same domain. Cookies are widely used for authentication, session management, user preferences, personalization, analytics, shopping carts, and remembering login information.

Unlike Local Storage and Session Storage, cookies are automatically included in HTTP requests, making them useful for maintaining server-side sessions. Modern browsers also provide security attributes such as Secure, HttpOnly, and SameSite to help protect user data.

Feature Description
Storage Type Small key-value pairs
JavaScript API document.cookie
Maximum Size Approximately 4 KB per cookie
Expiration Session or persistent
Automatically Sent to Server Yes
Common Uses Authentication, sessions, preferences, analytics

Common Cookie Use Cases

Application Purpose
User Login Maintain authenticated sessions.
Shopping Cart Remember cart items.
Theme Preference Store dark/light mode.
Language Preference Remember selected language.
Analytics Track anonymous visitors.
Remember Me Persist login information.
User Preferences Save UI settings.

Cookie Security Best Practices

Recommendation Reason
Use Secure Send cookies only over HTTPS.
Use HttpOnly Prevent JavaScript access to authentication cookies.
Use SameSite=Lax or Strict Reduce CSRF attacks.
Keep Cookies Small Improve request performance.
Never Store Passwords Protect sensitive information.
Encrypt Sensitive Values Reduce exposure if cookies are compromised.

Common Cookie Mistakes

  • Storing passwords or confidential information inside cookies.
  • Not using Secure for HTTPS websites.
  • Ignoring SameSite protection.
  • Using cookies for large amounts of data.
  • Forgetting to set expiration dates.
  • Not validating cookie values on the server.
  • Ignoring HttpOnly for authentication cookies.
  • Reading cookies repeatedly instead of caching values.

Key Takeaways

  • Cookies store small key-value data shared between browser and server.
  • document.cookie is used to create and read cookies in JavaScript.
  • Cookies automatically travel with HTTP requests.
  • Use cookies mainly for authentication and session management.
  • Prefer Local Storage for large client-side preferences.
  • Always use Secure, HttpOnly, and SameSite whenever appropriate.

Pro Tip

Store authentication tokens in secure, HttpOnly cookies whenever possible instead of Local Storage. This greatly reduces the risk of token theft through Cross-Site Scripting (XSS) attacks.