Hello and welcome computer geeks. In this post we are going to to learn how to add google authentication in node JS application. We will be going to use Passport JS. So let’s get started.

Requirements

There are two things required to add Google authentication in node JS project. The first thing is OAuth 2.0 client ID and client secret. The second thing is Passport JS npm package. So lets first generate OAuth 2.0 client ID and client secret.

How to generate Client ID & Client Secret

In order to generate them you have to go to this link and follow the below steps.

  1. Click on Create Credentials -> OAuth Client ID.
  2. Select Application type as Web Application.
  3. In redirection URL add http://localhost:3000/auth/google/callback
  4. Click on Create Button and it’s done.

Start Coding Authentication System

Initialize npm in your project: – First of all you have to initialise npm in your project with npm init -y command.

Install Packages: – Then you have to install some of the required packages and those required packages are express, passport and passport google auth. The following command will help you to do it.

npm install express passport passport-google-oauth

Create Web Server: – Now we are going to code a express.js web server so that we can respond to incoming requests. Block code is for creating a simple Express JS web server.

How to add Google Authentication in Node JS

Coding Passport JS

Now I am going to code Passport JS functionality. Below is the image for the whole coding of Passport JS. Don’t worry I will be explaining everything to you and I will also give you complete file download link.

In above code first I have a initialised passport and then initialised its session.

Then I am creating GoogleStartegy variable to define that we are going to use Google OAuth.

Then I am storing Google client ID and Google client secret that we have already made in a variable.

Then I am telling passport to use GoogleStartegy and passing client ID, client secret add callback URL in it. Then in callback function I am fetching profile detail of the user once he is a signed in and storing into userProfile variable.

Next in “/auth” route I am passing passport.authenticate function and in scope parameter I am accessing profile and email address of the user.

Once he or she is logged in will be redirect URL and our callback URL is simply standing or logged in text to Browser.

Below is the screenshot of how your sign in page will look like.

Download Project

Download code file from here.

Also Read: – Install Node JS & npm Cent OS 2021

Conclusion

I hope that this post was helpful for you and you found this content informative if you like my article then please share it with your friends and social media.

LEAVE A REPLY

Please enter your comment!
Please enter your name here