Tuesday, March 8, 2016

How gmail/google does mutiple user logins in the same browser

Have you ever wondered how gmail or google in general is able to log you in with two different accounts in the same browser (albeit different tabs)? For eg : a@gmail.com and b@gmail.com are able to login in the same browser at the same time.

Now why is it a big deal or to rephrase it, what stops any website to do the same and allow multiple user logins in the same browser.

The culprit is the cookie. Now for those who dont know how sessions work in web applications, once you visit/login to a website a session is created in the server and assigned a unique ID for each such session (user in our case). This ID is written to a cookie which the browser saves locally. When a request is sent from the browser to the server it also sends out the cookies which were set earlier by the browser and this is how the server understands who is calling the service. Is it a@gmail.com or b@gmail.com.

A cookie can be set at two levels (scope):


  • Domain: This means that all the requests originating from this browser for this domain would send all the cookies which were set for this domain. For eg: www.google.com
  • Path (or url): A cookie can be set at the url level too. What this means is we can set separate cookies for /url1  and /url2 (with same domain). When the browser sends a request for /url1 it would not send cookies set for /url2 to the server.
Most of the websites use a combination of the two.

Gmail or google uses the second approach to enable multiple login sessions from the same browser and the reason its able to do that is its a single page app. The url of gmail remains the same irrespective of the page you are on. For eg : Inbox would be https://mail.google.com/mail/u/0/#inbox  and sent items would be https://mail.google.com/mail/u/0/#sent. 

Now whatever is after # is not assumed to be a part of the url. So effectively no matter which page you are on, browser always thinks you are on the same url and send cookies set just for that url.

This is how gmail works. If you are logged in as two users, the urls would be  https://mail.google.com/mail/u/0/ and https://mail.google.com/mail/u/1/. Google assigns this number 0,1,2 for each user session and a separate cookie is set for each and voila you can now login as 2,3,4 different users in the same browser. To test this just change the number manually in one of the tabs, you would see yourself getting logged in as the other user.

This is possible only with a single page application like gmail where the url never changes. So if you want your application to support multiple logins, go single page!!