Google authentication Node.js and Express

ยท

3 min read

Google authentication Node.js and Express

Integrating social media authentication into your app involves using third-party authentication providers like Google or Facebook. Here, I'll guide you through adding Google OAuth authentication to a Node.js and Express application. You can follow a similar process for other social media platforms.

Step 1: Set Up Your Project

  1. Create a new project folder:

     mkdir social-authentication
     cd social-authentication
    
  2. Initialize a new Node.js project:

     npm init -y
    
  3. Install necessary dependencies:

     npm install express passport passport-google-oauth20 express-session
    

Step 2: Create Your Folder Structure

Create the following folder structure:

social-authentication/
|-- src/
|   |-- routes/
|       |-- index.js
|   |-- app.js
|-- server.js

Step 3: Set Up Express Server

In app.js, set up a basic Express server and middleware:

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const app = express();
const PORT = process.env.PORT || 3000;

app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

// Set up routes
const indexRoutes = require('./routes/index');
app.use('/', indexRoutes);

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 4: Set Up Google OAuth

Get your Google API credentials by creating a project on the Google Cloud Console:

  1. Create a new project.

  2. Enable the "Google+ API" for your project.

  3. Create credentials for a "Web application."

  4. Set the authorized redirect URI to http://localhost:3000/auth/google/callback (adjust the port if needed).

Step 5: Create Passport Strategy

In passport-setup.js (create this file in your project), set up the Google OAuth strategy:

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

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

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

passport.use(new GoogleStrategy({
  clientID: 'your-client-id',
  clientSecret: 'your-client-secret',
  callbackURL: 'http://localhost:3000/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
  // Store user information in the session
  return done(null, profile);
}));

Replace 'your-client-id' and 'your-client-secret' with the values from your Google API credentials.

Step 6: Set Up Routes

In routes/index.js, set up the routes for your social authentication:

const express = require('express');
const passport = require('passport');
const router = express.Router();

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

router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

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

router.get('/profile', (req, res) => {
  if (req.isAuthenticated()) {
    res.send(`<h1>Welcome, ${req.user.displayName}!</h1><a href="/logout">Logout</a>`);
  } else {
    res.redirect('/');
  }
});

router.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/');
});

module.exports = router;

Step 7: Create App Entry Point

In server.js, import and use the Express app along with the passport setup:

const app = require('./src/app');
require('./src/passport-setup');

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

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 8: Run Your Application

Start the Express server:

node server.js

Visit http://localhost:3000 in your browser. You should see a "Login with Google" link. After authenticating with Google, the user will be redirected to the /profile route displaying a welcome message.

Keep in mind that you may need to handle storing user data in a database and implement additional features depending on your application's requirements. Additionally, similar steps can be followed for other social media authentication providers by installing their respective Passport strategies.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย