# Integrate Google Oauth in your Node.Js applications

#### Google Oauth is an authentication API by Google which makes logging in easy for users as well as for developers for storing the user data.

Ever wondered how different sites use Google authentication in order to make your signup/login process a whole lot easier. Well, Google Oauth is something that they use in order to achieve this.

We are going to go step by step about how to apply this in your Node.Js applications using Passport.Js and Express.Js

First of all, making an app.js file in your root directly and starting a server using Express.Js and mongoose to connect to your MongoDB database. In order to do this, you’ll need to install all the npm dependencies. To initialize ‘npm’ in your project use in your terminal:

#### Workflow

![](https://cdn-images-1.medium.com/max/1600/1*CDWi2lZNnmE0Wu7s4v0CWA.jpeg align="center")

[https://phppot.com](https://phppot.com/php/php-google-oauth-login/)

### Project Initialization

```plaintext
npm init
```

and set all the options as per your wish, I usually keep them in their default state.

![](https://cdn-images-1.medium.com/max/1600/1*-hqNiho_mcnioFMY0nYWxw.png align="center")

You should be able to see something like this in your terminal.

After you are done with this NodeJs would create a package.json file for you, where all your dependencies and their versions should be visible.

After that use

```plaintext
npm i express mongoose body-parser dotenv
```

in order to install all the required dependencies to start a server and connect with MongoDB.

![](https://cdn-images-1.medium.com/max/1600/1*iPXf-sWhI8TlN0ONQlno8Q.png align="center")

### App.js initialization

Initialise your express server and MongoDB using the code below

```plaintext
const express = require(“express”);
const mongoose = require(“mongoose”);
const bodyParser = require(“body-parser”);
require(“dotenv”).config();
```

```plaintext
const app = express();
```

```plaintext
const dbURI = process.env.dbURI; //Add your database URL string here
```

```plaintext
mongoose
.connect(dbURI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
}).then(() => console.log(“Database Connected”))
.catch((err) => console.log(err));
```

```plaintext
mongoose.Promise = global.Promise;
```

```plaintext
//route not found
```

```plaintext
app.use((req, res, next) => {
const error = new Error(“Route not found”);
error.status = 404;
next(error);
});
```

```plaintext
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});
```

```plaintext
const PORT = process.env.PORT || 3000;
```

```plaintext
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
```

Your terminal should log when you use :

```plaintext
node app.js
```

![](https://cdn-images-1.medium.com/max/1600/1*bBCJdzJ5wVj13T_zEXqqPw.png align="center")

Voila! You’ve successfully initialised the server and connected your database

We need to make a user model in the models folder inside your root directory who is going to login to our app using Google Oauth having code :

### User model

```plaintext
const mongoose = require(“mongoose”);
const userSchema= mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
googleId: {type: String,},
name: { type: String },
email: {
type: String,
match: /[a-z0–9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-z0–9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-z0–9](?:[a-z0–9-]*[a-z0–9])?\.)+[a-z0–9](?:[a-z0–9-]*[a-z0–9])?/,
}
});
```

```plaintext
module.exports = mongoose.model(“User”, userSchema);
```

This is the user schema that we are going to use in order to store the user in our database

Create a routers model and add user.js and auth.js files to it, your directory should now look like :

![](https://cdn-images-1.medium.com/max/1600/1*JMLXd5za8dQrVhH-DIy_gg.png align="center")

After you’re done creating the model, it is time to explore the Google Oauth API

Go to

[console.developers.google.com](http://console.developers.google.com)

### Google API setup

#### Creating project and enabling API

![](https://cdn-images-1.medium.com/max/1600/0*1bq-Tngh6YIBRh3f align="center")

console.google.developers.com

Click on select a project and create a new project :

![](https://cdn-images-1.medium.com/max/1600/1*-5PU7sBiuzNqPSihNNV61g.png align="center")

console.developers.google.com

Enter your project name and organisation name if any :

![](https://cdn-images-1.medium.com/max/1600/1*Y2vww_putPvNU7SSYd9h4Q.png align="center")

console.developers.google.com

Now enable API and Services

![](https://cdn-images-1.medium.com/max/1600/1*uLBae2IP4CwtnEENfjMj1g.png align="center")

console.developers.google.com

Now search for Google+ and select the Google+ API and Enable it

![](https://cdn-images-1.medium.com/max/1600/1*E5bXnf0FQdUjX3RFqHfvcw.png align="center")

console.developers.google.com

You should be brought to a page like this and now click on create credentials

![](https://cdn-images-1.medium.com/max/1600/1*0Z4CMEjn1ZNkeX0y1ycnww.png align="center")

console.developers.google.com

select Google+ API on the form and save the access key somewhere with you .

#### Configuring and generating Credentials

You would then be redirected to a page like this and click on configure the consent screen

![](https://cdn-images-1.medium.com/max/1600/1*h8Twpaeryx68rFRmC92izA.png align="center")

Select *External* if you want all the Google users to be able to signup and fill the next page as shown by changing your project name

![](https://cdn-images-1.medium.com/max/1600/1*1cCzZfz7mFBB5HaXNVciWA.png align="center")

console.developers.google.com

![](https://cdn-images-1.medium.com/max/1600/1*-dQSJU8lDhRWEng6ooODhQ.png align="center")

console.developers.google.com

After you save it successfully, go to credentials page and click on *create credentials* and select OAuth *client ID*

![](https://cdn-images-1.medium.com/max/1600/1*l84uus5WcfAfNBjR4NRxxg.png align="center")

console.developers.google.com

Now this Form should open select your *application type* and enter your *application name*, now enter the URLs as I’ve done and you are good to go

![](https://cdn-images-1.medium.com/max/1600/1*k6VIqwnary94VpLRpIVU4A.png align="center")

console.developers.google.com

![](https://cdn-images-1.medium.com/max/1600/1*qPevoIy0Hd9QPOTPhZ2aQw.png align="center")

console.developers.google.com

A dialog box like this should occur with your credentials, make sure you save the credentials somewhere

![](https://cdn-images-1.medium.com/max/1600/1*llkOH9xCqDCm2Kva4WtxJw.png align="center")

console.developers.google.com

You are now all set on the Google developer console and now going back to VScode to setup our Passport.Js

Create a config folder in the root directory and add the passport-setup.js file to it.

```plaintext
npm i passport-google-oauth20
```

### Google-passport-setup

Now inside the ***passport-setup.js*** file add this snippet of code

```plaintext
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/user');
const mongoose = require('mongoose');
```

```plaintext
passport.serializeUser((user, done) => {
done(null, user.id);
});
```

```plaintext
passport.deserializeUser((id, done) => {
User.findById(id).then((user) => {
done(null, user);
});
});
```

```plaintext
passport.use(
```

```plaintext
new GoogleStrategy({
// options for google strategy
clientID: /* your clientID*/"" ,
clientSecret:/*your clienSecret*/"",
callbackURL: '/auth/google/redirect'
}, (accessToken, refreshToken, profile, done) => {
// check if user already exists in our own db
User.findOne({googleId: profile.id}).then((currentUser) => {
if(currentUser){
// already have this user
console.log('user is: ', currentUser);
done(null, currentUser);
} else {
// if not, create user in our db
new User({
_id: new mongoose.Types.ObjectId(),
googleId: profile.id,
name: profile.displayName,
email:profile._json.email
}).save().then((newUser) => {
console.log('created new user: ', newUser);
done(null, newUser);
});
}
});
})
);
```

Now explaining the snippet above, we first import all the necessary packages and file that we are going to use in the code. Enter your *clientID and clientSecret* that you received from Google developers console.

What is *callbackURL* — It is the URL on which Google will redirect your users to once they have successfully signedup/logged in. The access token is a token generated by Google which is automatically entered into the callback function in order to authenticate the user that just signed in, refreshTokens are used for offline apps, the profile is something that contains the user’s entire data which is returned from Google, I only took the data which my **user** model requires which is googleId, name and email but if you

```plaintext
console.log(profile)
```

you will get the entire user data that Google allows you to have.

The functions ***serializeUser and deserializeUser*** are used in order to generate cookies and actually get the user data when the user signs in so that he/she can be authenticated and the data could be further processed

### Routes and final setup

#### Auth Routes

Now in /routers/auth.js add this code :

```plaintext
const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");
```

```plaintext
const router = express.Router();
```

```plaintext
router.get("/google",passport.authenticate("google", {
scope: ["profile", "email"],
})
);
```

```plaintext
///Callback route for google to redirect
```

```plaintext
router.get("/google/redirect", passport.authenticate('google'),(req, res, next) => {
user = req.user
res.send(user)
});
```

```plaintext
module.exports = router;
```

The ***scope*** used in router.get(“/Google”…..) is to define which data fields we actually require from Google according to the profile in the callback function as we recall

It will automatically redirect you to /auth/Google/redirect as we added that to the callbackURL in the GoogleStrategy function in passport-setup.js

#### App.js Final additions

Now in app.js add this snippet of code before calling the mongoose.connect() function:

```plaintext
const passportSetup = require(".config/passport-setup");
const passport = require("passport");
```

```plaintext
const authRoutes = require(".routers/auth");
```

```plaintext
// initialize passport
app.use(passport.initialize());
app.use(passport.session());
```

```plaintext
app.use("/auth", authRoutes);
```

app.use(“/auth”,…..) because the URL to redirect to Google signup/login using [***http://localhost:3000/auth/Google***](http://localhost:3000/auth/google)

### Testing and checks

you now run the app using node app.js you should still see the same console.log() which you saw in the beginning. Now open your browser and go to [***http://localhost:3000/auth/Google***](http://localhost:3000/auth/google)***,*** It should redirect you to the Google sign-in page

![](https://cdn-images-1.medium.com/max/1600/1*-BIb025qHbp0PYNHYmo2gg.png align="center")

accounts.google.com

Once you select any account it should redirect you to router.get(‘/Google/redirect’,…..) in which we sent the data of the user as a response, you can redirect directly from there using res.redirect too.

but what we have kept should display an output page like

![](https://cdn-images-1.medium.com/max/1600/1*fOgpluYPNxQKa0-dB9Xazg.png align="center")

which has already been saved to the database you created.

Congrats you’ve successfully integrated the Google Oauth API in your nodejs application.

Github repository link : [https://github.com/jugaldb](https://github.com/jugaldb/Google-Oauth-NodeJs)/Google-Oauth-Nodejs
