Cookies and sessions

Why doesn't Facebook ask you to log in every time?

Demo 4 of 7Reel"Bakit hindi ka na pinapa-login ulit ng Facebook?"

Try it

Log in with any name, then reload the page. You stay logged in because your browser sends a cookie with every request.

GET /api/lab/session

Checking for a session

Your browser

No lab_session cookie yet. Log in and the server sets one.

The server

No session row. Nobody is logged in from this browser.

Requests

Nothing sent yet.

What just happened

When you log in, the server makes a session, a long random id that points to who you are. It hands that id to your browser in a cookie.

From then on your browser sends the cookie back with every request, and the server looks the id up. You never send your password again, only the id.

The cookie here is httpOnly, so scripts running on the page can't read it. That stops a malicious script from stealing your session and logging in as you.

Where you've seen it

  • Staying logged in after you close the app
  • "Log out of all devices", which deletes every session the server has for you

Keep going