How to Add Google Authentication in Node Application

Ayumi Tanaka
5 min readJun 4, 2021

Photo by Firmbee.com on Unsplash

This article explains how to add Google authentication such as login function in the Node.js application.

1. Set up a project

First thing first, let’s create a project directory and install packages.

  1. Create a project directory, then type npm init -y to create a package.json file in your terminal.
  2. Create index.js and passport-setup.js.
  3. Install libraries. You can copy and paste this command. npm i express cors nodemon cookie-session passport passport-google-oauth20.
  4. Go to package.json and make sure that you successfully installed these libraries, then change your "scripts" to "start" : "nodemon index.js".
4

2. Create a base for Index.js

Next, create basic routes in index.js.

  1. Import libraries, express, cors, passport, cookie-session.
  2. Define const app = express().
  3. To allow all APIs to be CORS-allowed, write app.use(cors()).
  4. To parse the application, URL encoded, JSON, write app.use(express.urlencoded({extended:false}) app.use(express.json().
  5. Create a top route. You may send some random text to test, something like app.get("/", (req, res) => res.send("Hello World")).
  6. To bind and listen the connections on the specified host and port, write app.listen(3000, ()=> console.log(`Example app listening on port ${3000}!`).
  7. Now you can try npm start then you’ll see “Example app listening on port ${3000}!” if it’s working correctly. Also, you can access localhost:3000 and you’ll see “Hello World”!
7

3. Create a base for passport-setup.js

Next, create basic functions in passport-setup.js.

  1. Go to Passport documentation. Copy configuration and paste it into your file. You may change var to const.
  2. Since we installed passport-google-oauth20, change second line to const GoogleStrategy = require("passport-google-oauth20").Strategy.

4. Create a Credential key on GCP

Next, create a credential key on the Google Cloud Platform. You might need to create a project.

  1. After login with Google Account, click “CREATE PROJECT”.
  2. Name “Project name” and choose “Location” if you have, then click “CREATE”.
  3. Click “API & Services”.
  4. Click “OAuth consent screen”, and choose “External” as user type, then click “CREATE”.
  5. Input your “App name”, “User support email”, and “Developer contact information” down below, then click “SAVE AND CONTINUE”.
  6. About scopes — Just click “SAVE AND CONTINUE”.
  7. About test users — Just click “SAVE AND CONTINUE”.
  8. After you see the summary, you can click “CREATE CREDENTIALS”, then click “OAuth client ID”.
  9. Choose “Web application”.
  10. Name app name whatever you like, then add “URIs” for “Authorized redirect URIs” down below. You can input http://localhost:3000/google/ and http://localhost:3000/google/callback.
  11. You’ll see your ID and Key.
  12. You need to copy and paste them on your passport-setup.js file.
1
2
3
4
5
6
7
8
9
10
11
12

5. Implement index.js

Next, let’s implement routes and functions in index.js.

  1. To use passport from passport-setup.js, write require("./passport-setup").
  2. Go to Passport documentation. Copy roures and paste it into your file. Plese make sure to paste before app.listen().
  3. Since we set up route as http://localhost:3000/google/ and http://localhost:3000/google/callback on GCP (4–10), change routes from /auth/google to just /google, and from /auth/google/callback to /google/callback.
  4. For the first authenticate mehod, change scope scope: ["https://..."] to ["profile", "email"].
  5. For the second authenticate mehod, change failureRedirect: "/login" to failureRedirect: "/failed", and res.redirect("/succeed").
  6. Create "/failed" and "/succeed" routes.
  7. Go to Passport documentation. To initializes passport and passport sessions, copy two lines in middleware and paste it into your file.
  8. Go to Cookie-Session package page. Copy app.use() and paste it into your file. For an actual app you should configure this with an experation time, better keys, proxy and secure.
2
3, 4, 5
7
8
6, 7, 8

6. Implement index.js

Next, let’s implement functions in passport-setup.js. Since we don’t use db for this, I’ll code this demo app as simple as possible. So that some functions might not work for the real full-stack app. In that case, please read docs carefully.

  1. Change callbackURL: "http://www.example.com..." to callbackURL: "http://localhost:3000/google/callback" in passport.use().
  2. Also, change inside function, just return done(null, profile).
  3. Go to Passport documentation. Copy sessions and paste it into your file.
  4. Change inside passport.serializeUser(), user.id to user.
  5. Change passport.deserializeUser(), functionser(user, done)to functionser(id, done). Inside function, delete them all and just write done(null, user).
3
1, 2, 4, 5

7. Done!

Let’s test it out! Go to http://localhost:3000/google and try Google login. Hope you can see “Succeed!”.

8. Source

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response