How to set up a single sign-on with Google using Node JS and React JS?

How to set up a single sign-on with Google using Node JS and React JS?

Enabling Google Sign-In and Sign-Up in a Node.js and React.js web application involves setting up authentication using Google's OAuth 2.0. Below is a step-by-step guide to implement this.

Step 1: Set Up Google Developer Console

  1. Create a New Project:

    • Go to the Google Developer Console.

    • Click on the project dropdown and select "New Project".

    • Name your project and click "Create".

  2. Enable OAuth 2.0:

    • Navigate to the Credentials section.

    • Click on Create Credentials and select OAuth 2.0 Client IDs.

    • Configure the consent screen with your application details.

    • Set the Authorized redirect URIs to the URL where you will handle the OAuth 2.0 response (e.g., http://localhost:3000/auth/google/callback).

  3. Get Client ID and Client Secret:

    • After creating the credentials, you will get a Client ID and Client Secret. Note these down as you'll need them later.

Step 2: Set Up the Backend (Node.js)

  1. Initialize a Node.js Project:

     mkdir myapp
     cd myapp
     npm init -y
    
  2. Install Required Packages:

     npm install express passport passport-google-oauth20 cookie-session
    
  3. Create index.js:

     const express = require('express');
     const passport = require('passport');
     const GoogleStrategy = require('passport-google-oauth20').Strategy;
     const cookieSession = require('cookie-session');
    
     const app = express();
    
     // Replace with your Google client ID and client secret
     const GOOGLE_CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
     const GOOGLE_CLIENT_SECRET = 'YOUR_GOOGLE_CLIENT_SECRET';
    
     app.use(cookieSession({
         name: 'session',
         keys: ['key1', 'key2']
     }));
    
     app.use(passport.initialize());
     app.use(passport.session());
    
     passport.serializeUser((user, done) => {
         done(null, user);
     });
    
     passport.deserializeUser((user, done) => {
         done(null, user);
     });
    
     passport.use(new GoogleStrategy({
         clientID: GOOGLE_CLIENT_ID,
         clientSecret: GOOGLE_CLIENT_SECRET,
         callbackURL: '/auth/google/callback'
     },
     (accessToken, refreshToken, profile, done) => {
         return done(null, profile);
     }));
    
     app.get('/auth/google',
         passport.authenticate('google', { scope: ['profile', 'email'] })
     );
    
     app.get('/auth/google/callback',
         passport.authenticate('google', { failureRedirect: '/' }),
         (req, res) => {
             res.redirect('/');
         }
     );
    
     app.get('/', (req, res) => {
         res.send(`<h1>Hello ${req.user ? req.user.displayName : 'Guest'}</h1>
                   <a href="/auth/google">Sign In with Google</a>`);
     });
    
     app.listen(3000, () => {
         console.log('Server is running on http://localhost:3000');
     });
    

Step 3: Set Up the Frontend (React.js)

  1. Create a React App:

     npx create-react-app myapp-frontend
     cd myapp-frontend
    
  2. Create a Google Login Component:

    1. Install react-oauth/google package:

       npm install @react-oauth/google
      
    2. Modify src/App.js:

       import React, { useEffect, useState } from 'react';
       import { GoogleLogin } from '@react-oauth/google';
       import jwt_decode from "jwt-decode";
      
       function App() {
           const [user, setUser] = useState(null);
      
           const handleLogin = (credentialResponse) => {
               const decoded = jwt_decode(credentialResponse.credential);
               console.log(decoded);
               setUser(decoded);
           };
      
           const handleError = () => {
               console.log('Login Failed');
           };
      
           return (
               <div className="App">
                   <h1>Hello {user ? user.name : 'Guest'}</h1>
                   {!user && (
                       <GoogleLogin
                           onSuccess={handleLogin}
                           onError={handleError}
                       />
                   )}
               </div>
           );
       }
      
       export default App;
      
    3. Add the Google Client ID to src/index.js:

       import React from 'react';
       import ReactDOM from 'react-dom';
       import { GoogleOAuthProvider } from '@react-oauth/google';
       import App from './App';
      
       const GOOGLE_CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
      
       ReactDOM.render(
           <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
               <App />
           </GoogleOAuthProvider>,
           document.getElementById('root')
       );
      
  3. Run Your React App:

     npm start
    

Summary

  1. Set up Google Developer Console: Create a project, enable OAuth 2.0, and get your Client ID and Client Secret.

  2. Backend with Node.js: Use Express and Passport.js to handle Google OAuth authentication.

  3. Frontend with React.js: Use the @react-oauth/google package to handle Google Sign-In.

With these steps, your Node.js backend will handle the authentication process, and your React frontend will provide a smooth user interface for Google Sign-In.