Search code examples
expresscookiesexpress-sessioncookie-session

Isn't cookie-session in express essentialy the same as JWT tokens?


In the express documentation a distinction is made between express-session and cookie-session. There it says:

A user session can be stored in two main ways with cookies: on the server or on the client. This [cookie-session] module stores the session data on the client within a cookie, while a module like >express-session stores only a >session identifier on the client within a cookie and stores the session >data on the server, typically in >a database.

Aren't JWT tokens also just storing all the session data in a cookie and what might distinguish JWTs from the cookie-session module?


Solution

  • The main difference between express-session and cookie-session is how they save cookie session data.

    The express-session middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you’ll need to set up a scalable session-store like database.

    In contrast, cookie-session middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects).

    While JWTs provide a means of maintaining session state on the client instead of doing it on the server, it's just a token with payload data containing user, created time, etc (which should not be sensitive). JWT usually used for authorization, is sent to the server via bearer token in Authorization header. Browser will automatically send cookies with each request to the server when using cookie-session module, but bearer tokens need to be added explicitly to the HTTP header while making request.