Setting Up Google OAuth Using Passport.js in your Node Application

Photo by Mitchell Luo on Unsplash

Many of you might have come across web applications that present you with the option to sign up or sign in using either Google, Github, Facebook, or any other external application. And if you are here, it means you want to know how it is done.

We will be implementing the google OAuth sign-in process but before going into the practical application; I’ll define and hopefully, simplify some terms that we will be using often in this tutorial.

In our project, we are considerate developers and we do not want our users to go through the tedious process of filling out forms and whatnot. What we want to do is present them with a simple alternative — so we are telling them that we see that they want access to our brilliant application and we are going to make it easy for them to get that access. All they need to do is click our little “Login with Google” button and permit us to use their information to create an account for them.

This tutorial assumes you have knowledge of Express.js, you have your user's database setup or you understand references made to a database and you understand routes and how they are used in a frontend application. It also assumes that you have your secretKey and clientID from your google console. The purpose of this article is to simplify the process of setting up Passport in your Node application.

First things first, we are going to install everything our application is going to need.

Passport.js: npm install passport

Passport google strategy: npm install passport-google-oauth

Express: npm install express

We are going to set up our application;

const express = require("express");
const passport = require("passport");
const app = express();app.listen(5000, () => {
console.log("now listening for requests on port 5000");
});

Once we are certain our application is running on our specified port, the next thing we are going to do is instruct our app to use Passport and we will then initialize Passport.

const express = require("express");
const passport = require("passport");
const app = express();app.use(passport.initialize()); //initializes passportapp.listen(5000, () => {
console.log("now listening for requests on port 5000");
});

Now we have set up our application and we have told our application to use Passport. Remember that we also installed the google strategy from the many different strategies that we have. To use it, we are going to require it into our application.

const GoogleStrategy = require("passport-google-oauth20").Strategy;

After doing that, we will tell Passport “Hey, this is the google strategy. I want you to use it”.

passport.use(//the rest of our code goes in here);

Passport now knows that it has to use something but for Passport to use our Google Strategy, we have to do one thing. We have to create a new instance of the Google Strategy we required into our application.

passport.use(
new GoogleStrategy({
//the rest of our code goes in here}));

The new GoogleStrategy that we have initialized takes in two parameters. The first one is an object containing the ClientID and the ClientSecret that we retrieved from google, as well as our callback URL.

The second parameter is a callback function that takes in the following parameters; access token, refresh token, profile, and done. In this tutorial, we are only going to concern ourselves with two out of these four parameters and those are profile and done.

passport.use(
new GoogleStrategy({
clientID: yourClientID,
clientSecret: yourClientSecret,
callbackURL: "/auth/google/callback",
}}
}));

This is our first parameter. So what we are doing here is simple. We are creating a new instance of our Google Strategy and then telling Passport to use this instance for authentication. In this instance, we are telling this strategy our id, and our special secret that is all particular to us — and we are finally putting in a URL that our user would be redirected to after successful authentication.

passport.use(
new GoogleStrategy({
clientID: yourClientID,
clientSecret: yourClientSecret,
callbackURL: "/auth/google/callback",
},
(profile, done) => {
const existingUser = () => User.findOne({ googleId: profile.id });
if (existingUser) {
// we already have a record with the given profile ID return done(null, existingUser);
}
// we don't have a user record with this ID, make a new record
const user = await new User({ googleId: profile.id }).save(); done(null, user);
}));

In our second parameter, we have a callback function taking in two parameters; profile and done. Profile as you must have guessed it is the user’s profile and done here is well — done. What we are doing in that block of code is first of all looking through some users we have stored in our database and checking to see if we have one with the id of whoever is trying to get into our application. We want to see if the user exists in the database.

If yes, we are going to call done and pass in the user. If no, we are going to create a new record of the user in the database.

Passport has now been set up in our application. It has all our basic instructions and it is ready to start carrying out its duties. But not so fast! We need to set up our routes.

module.exports = (app) => {
app.get("/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"],
}));
app.get("/auth/google/callback",
passport.authenticate("google"),
req, res) => {
res.redirect("/redirectURL");
});
};

In the code we have above, we have set up two routes. The first route “/auth/google” and the second route “/auth/google/callback”. The callback route if you remember, is the one that redirects our user after authentication has been successful.

We are also calling the authenticate method on Passport. Looks strange, doesn’t it? I mean where is the google string coming from?

Well, it is rather simple. We are telling passport “Hey, there is some authentication that needs to be done and we are going to be using the google strategy to achieve this”. Just your everyday conversation.

The first route is what will be attached to our button. On click of our button, we will be redirected to the page, you might have seen this at some point while trying to sign-in or sign-up into an application.

Passport understands our instruction but isn’t exactly sure what it is we want to get from google specifically. That is where the scope comes in, scope tells Passport what specific information we would like to get from our user.

So far so good. We have been able to setup Passport.js in our application. The next line of action would be to test it out using the routes in the frontend of our applications.

Hello! I am a frontend developer trying what she can to simplify all things techy. Sharing all things learnt one at a time.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store