Login with Google (Code to Access Token) — Any client to Any server

There are a lot of Login with Google tutorials, posts, videos, libraries on the Internet. But there seem to be almost zero articles about how to get a code from client and send it to the server, where the server fetches the tokens. Especially ones that work.

Luckily this story will cover just that. We will have a JavaScript client with a login to Google that will get a code and it send it to an ExpressJS server where that server will return us the access token back.

Do note that this is just for demo purposes, to show you how it works in code. Whatever you do with it is up to you.

Photo by marcos mayer on Unsplash

Before starting

Please create an OAuth client on Google Cloud console. You will need the Client ID and the Secret.


The client in our case will be a simple html page. You can make it whatever you want. Just get the code from Google and you are ready.

It’s important to call grantOfflineAccess as that will let Google know that we want the code back, not the profile info.

Once you get the code back, you can submit it to your backend server. Again this is the CODE flow of authentication.

In Google’s authentication code flow it is required for the redirect_uri to be ‘postmessage’ instead of a URI.


Our server will run on port 8080, and it will have just one route, as that is all we need for this demonstration. The goal of the server, whatever the stack, is that it receives the code, fetches the access token and then does whatever it likes. For example: you can store the tokens (access, refresh, expiration) for later use. Create a user with the profile info and return the user info back or just return your own JWT token back.

The important part is that this is Server side. Client already accepted our app, we already got the code, there is no callback url needed. In simple terms, we have the code, now give us the tokens based on it.

If you have the client and the server on the same domain. Like running a Ruby on Rails app or Express serving client, then yes, callback url is the way to go. But we are not doing that here. In our case the client is separated, we can’t use the callback, as the server would not know which client requested it.

Of course, this can be handled on all on the client. But we want to access users info when the user is not present on the site. In other words and ‘offline’ access.

Thats it. Whole code can be fund here: https://github.com/zprima/js-google-code-to-token