Would not it be better to store user id instead of session id so that we only lookup database once for extracting other user info instead of twice extracting user id from session db then user db?

  • But a cookie is supposed to be short-lived. If you're not storing the sessionID then how do you know if a cookie is expired? Aug 22, 2018 at 16:58
  • 3
    User ids are usually predictable and difficult to revoke, take a look at session hijacking. Aug 22, 2018 at 16:58
  • Ah yes i understand so it is related to expiration purposes, could i store other info then inside the session database along with user id to track user behavior ?
    – Dodz
    Aug 22, 2018 at 17:01

2 Answers 2


That would be a very bad idea because a malicious user could change the id they are sending.

If for example the admin has the id 1, and a user the id 101, that user could simply change their id in the cookie to 1, and thus gain admin privileges.

For the same reason, you would not want to send any other relevant data in cookies, as you cannot trust this data (unless it's signed and thus cannot be altered, eg using jwt).

You could of course generate random user ids. But even if we assume that these are unguessable, this would be problematic. It would essentially be the same as if you were sending the password in a cookie. If an id leaks even once, an attacker would gain permanent access as it is unrevokable. Session ids on the other hand expire after a while or can be revoked.

  • Could i store other info then inside session database along with user id to track user behavior ?
    – Dodz
    Aug 22, 2018 at 17:29
  • @Dodz It probably depends on the details of the implementation, but at least in general, I don't see why not.
    – tim
    Aug 22, 2018 at 18:12

The user ID is a constant value in the database which isn't what you want for handling session tokens in cookies, as the session ID has to change frequently.

As @AndrolGenhald has said, the user ID in a database will probably be easy to predict as it will likely be a number which simply increments with new users. A session ID on the other hand will have a high entropy such that it is very difficult to guess the value of a session ID.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .