Creating a Simple Node.js App with Google OAuth 2.0 Authentication

Providing users with a seamless login experience is crucial. One popular method is to allow users to log in using their Google accounts. A developer reached out to me this week asking if I knew how to set up google oauth for signing into a website. It can be a pretty confusing task if you haven’t done it before. In this blog post, I’ll walk you through creating a simple Node.js application that integrates Google OAuth 2.0 authentication. Once users log in, they’ll be greeted with a page displaying their email.

1. Setting Up Google Developer Console:

  • Navigate to the Google Developer Console.
  • Start by creating a new project.
  • Head over to the OAuth consent screen and provide the necessary details.

    Note: If you are using this guide and keep the localhost domain, for the app name, use the app id. Not sure why this works but it is the only way I can get it to use the localhost domain.
  • Create OAuth 2.0 client IDs. Opt for the “Web application” and set the authorized redirect URIs to http://localhost:3000/auth/google/callback.
  • Make sure to note down your Client ID and Client Secret as they’ll be used later.

2. Preparing the Node.js Environment:

  • Initialize a new npm project with:
npm init -y
  • Install the required packages using:
npm install express passport passport-google-oauth20 express-session ejs

3. Crafting the Express Server:

Your main server file, server.js, will handle the routes and authentication process. The code provided earlier in this guide sets up the Express server, integrates Passport for authentication, and uses the GoogleStrategy for OAuth.

const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const session = require('express-session');

const app = express();

app.set('view engine', 'ejs');

app.use(session({
    secret: 'secret_key',
    resave: false,
    saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

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

passport.deserializeUser((obj, done) => {
    done(null, obj);
});

passport.use(new GoogleStrategy({
    clientID: 'YOUR_GOOGLE_CLIENT_ID',
    clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
}, (token, tokenSecret, profile, done) => {
    return done(null, profile);
}));

app.get('/auth/google',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email'] })
);

app.get('/auth/google/callback', 
    passport.authenticate('google', { failureRedirect: '/' }),
    (req, res) => {
        res.redirect('/profile');
    }
);

app.get('/profile', (req, res) => {
    if (!req.isAuthenticated()) {
        return res.redirect('/');
    }
    res.render('profile', { email: req.user.emails[0].value });
});

app.get('/', (req, res) => {
    res.send('<a href="/auth/google">Login with Google</a>');
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

The route /auth/google initiates the Google authentication process, while /auth/google/callback handles the callback after Google has authenticated the user. If the authentication is successful, the user is redirected to the /profile route, where their email is displayed.

4. Designing the User Profile Page:

Using EJS as our templating engine, we’ve created a simple profile page (views/profile.ejs) that displays the user’s email once they’re logged in.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Profile</title>
</head>
<body>
    <h1>Welcome!</h1>
    <p>Your email: <%= email %></p>
</body>
</html>

5. Running the Application:

  • Start your server using node server.js.
  • Open your browser and visit http://localhost:3000.
  • Click on “Login with Google” and go through the authentication process.
  • Upon successful authentication, you’ll land on a profile page showcasing your email.

Important: Don’t forget to replace 'YOUR_GOOGLE_CLIENT_ID' and 'YOUR_GOOGLE_CLIENT_SECRET' in the server.js file with the actual values you obtained from the Google Developer Console.


Integrating Google OAuth 2.0 authentication in a Node.js application is straightforward with the right tools. This guide provides a basic setup, but in real-world applications, you might want to add more features like database integration, enhanced security, and more.