Cookies vs. Sessions: When to Use Each for Web Development

Han Lin AungHan Lin Aung
2 min read

REST APIs are designed to be stateless. That means server does not save the user context between requests. To identifies the user, the client should includes credentials like token and api keys in each request to maintain the RESTful principle.

There are two primary mechanism mainly used to address this. Cookies and Server Session

  • Cookies are small amount of data that sent from server and save in the client-side(browser) and then send back to server with every request.

  • Sessions are user data that are bind with a unique ID and store in server side (i.e in memory , database or cache)

Key Differences

Storage

  • Cookies are stored in client-side (browser) and it can only store a small amount of data ( max 4KB )

  • Sessions are stored in server-side (in-memory, database, cache) and it can store larger amount of data

Security

  • Cookies are less secure as it’s exposed to client but can be used with security flags such as httpOnly, same-site, secure

  • Sessions are more secure as it’s stored in server and only session Id is exposed to client.

Time-To-Live

  • Cookies’ lifespan can be set using max-age : (total duration of time that it will live in seconds) and expire : (date when it expires i.e 25th September, 2025). Cookies are persistent even after the browser is closed until it expires.

  • Sessions are lost when the user doesn’t interact with web server for a certain amount time, when the user logout or the server restart. Session TTL can be configure depends on the language server you are using. You can store session data in database such as Redis to keep the session between server restart or as a centralized storage in a distributed system.

Use Cases

Cookies

  • Use for small and repetitive data such as session IDs and tokens for authentication.

  • Use for user’s preference data such as theme and language settings ( can use new client-side storage apis such as localStorage and sessionStorage)

  • Use for data that required to be persistent across sessions.

Sessions

  • Use for sensitive data such as authentication data and payment info

  • Use for temporary data such as password reset token

  • Use for large amount of secure data such as authenticated user’s shopping cart items

Conclusion

While cookies and session both manage state. Cookies are ideal for non sensitive, small amount of data and Sessions store secure, sensitive and large amount of data. Alternatively JsonWebToken ( JWT ) are preferred over server session as it follow the stateless principle.

0
Subscribe to my newsletter

Read articles from Han Lin Aung directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Han Lin Aung
Han Lin Aung