Authentication using Google’s oAuth api with node.js

OAuth authentications are pretty popular now a days and another thing which is popular is JavaScript. This article shows how to plugin google’s oAuth api for authentication in your own node application. The github repo is also available.

A background of oAuth

OAuth is an authentication technique which provides you a secure and delegate access to some server resources on behalf of the resource owner. This is a very commonly used technique in third party websites to authenticate a user via his/her facebook, twitter or google account, without disclosing the password and also without taking the headache of storing user credentials in their websites.

Get the client-id and client-secret

To use oAuth (or any other api) of google you need to create an app in google developers console. Follow the steps below, described in the images and you will be able to generate the client-id and client-secret.








Code in node for OAuth

I am describing things here with a small node/express application which has few routes and returns normal html with some links. However you can implement the same thing may be in a popup window or wherever you needed.

Install express and googleapis modules

Let us also install express’s session plugin which I will describe later on, why it was necessary.

I will be using only one file, that is server.js. All the codes below will go into that only.

Setup the basic app

create oAuth url

The function getOAuthClient() creates an oAuth client and the getAuthUrl() function creates the url to be hit for authentication.

Let’s link that url to our base route.

If you run the node server.js now, it will look like the following image.


Things you need to know about scopes

Scopes are like permissions. What kind of permissions do you want from the user? Is it just the identity and basic details of him (for which I am using the scope), or calendar (‘‘) or drive or something else. Just remember to enable that scope from developers console. How to enable is shown in the images below.



The callback route

If you remember, while creating the client id and secret in google’s developer console, we provided the callback link. So now it’s time to actually develop that route.

So, we are creating a route oauthCallback which is used as a callback in out google app where we are receiving the code which is being provided by google as a query parameter; and using that we are fetching the access token and saving that token to the current user session.

A successful login will redirect you to the following page.


Fetch user data

So if the login is successful, let us fetch some details of that user using google apis. Below is the code for the /details route.

We’re just getting the saved token back from session and using that we’re fetching the user details. If things run good, you will see a details page like following.


Entire server.js


So, why we saved the token in session? The reason is, if we didn’t save the token in session and just set it to the oauth2Client, it would have been gone by next request as every router hit creates the oauth2Client again. If you set oauth2Client globally, than if a person A logs in, it will automatically reflect to person B’s computer.

Google apis are not just for authentication, they are for many more. You can check them in their github repo. Just like a very similar approach to google’s OAuth, you can also integrate facebook, twitter oAuth apis too with their respective node modules.

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.

  • Wouter Nieuwerth

    Thanks a lot for the instructions!

    I was just wondering, in one of the screenshots you erased the ClientID and ClientSecret, while in the final code example they are both visible. Accident?

    • Paul Shan

      Yup accident. Thanks for notifying.

  • Anand Duddella

    Thank you for the example. I am using your code as it is and the callback route is not called. The flow is I click the link , browser redirects me google and once i accept the callback fails with a HTTP 500 error. I have even tried console logging into the callback route function but it seems that it never gets invoked.

    I would have the following in the url

    http://localhost:3000/googlecallback?code=%5Bmy code]

    and the get route code is as below

    app.use(“/googlecallback”, function(req, res) {
    var oauth2Client = getOAuthClient();
    var session = req.session;
    var code = req.query.code;
    oauth2Client.getToken(code, function(err, tokens) {
    // Now tokens contains an access_token and an optional refresh_token. Save them.
    if (!err) {
    session[“tokens”] = tokens;
    res.send(‘User Authenticated’);
    } else {
    res.send(‘User Authentication failed’);

    Any help would be greatly appreciated.

    • Paul Shan

      Hi Anand, sorry I was not much involved in voidcanvas for the past 6 months. Probably you’ve fixed the error by now, but still if there is any issue we can talk.

  • Ali Poder

    for those who worries about memory leak, don’t worry, nodejs garbage collector will handle it.

  • Paul Shan

    this should be the output. You need to click on the login link.

  • Paul Shan

    host your code somewhere and provide the link

  • Axel Adam

    many thanks. works perfectly.

  • Alex McLeod

    Since the author hasn’t answered this yet, and it happened to me too, I’ll post this here so you people reading the comments know. < and > render as a printed . You want to put the symbols instead, so that it’ll read it as html.

  • Paul Shan

    Ahh.. not sure about the though. Hope people will understand this.

  • rahul


  • When I use “oauth2Client.getToken(req.query.code)” I get the error “UnhandledPromiseRejectionWarning: Error: invalid_grant”. Anyone had this?

  • jayanthi naik

    Can I get gmail id once authentiction done?

  • Parth Kanani

    After trying your code i am getting output as Hello “undefined” that is its not fetching the data after even login Do i have to make any changes in the code??