Google OAuth2 with NodeJS-Simplified!

Adarsh C
2 min readJun 11, 2021
google oauth2

Every modern application allows its users to sign-up through Google. But why?

  1. Eradicate separate credentials
  2. Ease of Login
  3. Access to user’s profile

So it’s a no-brainer to integrate with these services.

The way to go about this on NodeJS from a very long time was to use a library like PassportJS, implement one of its strategies and never worry about authentication again. It seamlessly worked with popular templating engines like EJS, Pug or Jade. However, if you’re using a framework like NextJS, which is known for its Server-Side Rendering capabilities, you’re in trouble. I was frustrated initially, but later realized that PassportJS was not the tool for the job.

Unfortunately, there are no plug-play libraries for this flow and Google’s OAuth Node APIs weren’t great either. This is when I decided to write an NPM package which provides a level of abstraction for future developers who are adopting this flow.

So let’s first try to understand the flow of this authentication process with this sequence diagram.

oauth sequence diagram

You can further refer to this article to know more about OAuth2 Protocol.

As complex as it may seem, you can easily implement this authentication system with just a few lines of code. So let’s dive right in!

Let’s first install the package.

npm install node-google-oauth2

Now, we have to create an instance of the class by passing a few constructor parameters. These params are clientID, clientSecret, and redirect. These values can be obtained in your Google Cloud Platform dashboard. For detailed instructions, refer to this article.

Make sure to store them as environment variables.

Next, when the client sends a request for Authentication, we should obtain a URL from Google’s OAuth Server and return it to the client.

Then, the client can redirect the user to that link, where our user can authorise us to access their data. We should now anticipate a redirect to the route we specified earlier, and handle the request.

We now have access to the payload which contains the profile details of the user, such as email, profile-image url, first and last names etc. This should be enough for us to populate our database.

That’s it! You can now add custom middlewares and controllers on top of this to build a robust authentication system.

Thanks for reading the article. If you found this insightful, please share it with your friends. Also check out Hover Studio, a digital agency where we build amazing products, websites and much more✨

Github Repo: https://github.com/CAdarsh/node-google-oauth2

--

--