Implementing Google Login with Redirect-Based Approach in ReactJS

yusufginanjar

Yusuf Ginanjar

Posted on May 19, 2024

Implementing Google Login with Redirect-Based Approach in ReactJS

Social logins, like login with Google, can significantly improve the user experience. By offering a simpler registration and login process, social logins reduce friction and make it easier for users to access your application. Many users, myself included, prefer social authorization over manual registration because it saves time and eliminates the need to remember yet another username and password.

OAuth 2.0 is a protocol that enables applications to securely access resources (like user information) on a user's behalf with their consent.

Here are the steps involved in developing login with Google using the redirect-based approach:

Implementation

1. React Js Implementation

Create route /login to access Login.jsx and /auth/success to access LoginSuccess.jsx

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route path="login" element={<Login />} />
          <Route path="auth/success" element={<LoginSuccess />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode

Install Packages

npm install react-router-dom axios
Enter fullscreen mode Exit fullscreen mode

Create a React component Login.jsx to handle the login functionality:

import React from 'react';
import { Link } from 'react-router-dom';

const clientId = 'YOUR_GOOGLE_CLIENT_ID'; // Replace with your actual client ID
const redirectUri = 'http://localhost:5000/callback'; // Replace with your redirect URI

const Login = () => {
  const handleLogin = () => {
    const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=<span class="math-inline">\{clientId\}&redirect\_uri\=</span>{redirectUri}&response_type=code&scope=openid%20profile%20email`;
    window.location.href = googleAuthUrl;
  };

  return (
    <div className="login-container">
      <h1>Login with Google</h1>
      <button onClick={handleLogin}>Sign in with Google</button>
      <p>
        By clicking "Sign in with Google," you agree to our terms of service and privacy policy.
      </p>
    </div>
  );
};

export default Login;


Enter fullscreen mode Exit fullscreen mode

Create a React component LoginSuccess.jsx to handle the login success and catch the token:

import { useEffect } from "react";

const LoginSuccess = (props) => {
    useEffect(() => {
        const token = new URLSearchParams(window.location.search).get("token");
        if (!token) {
            window.location.href = "/login";
        }
        localStorage.setItem("TOKEN", token);
                console.log(token);
    }, []);

    return (
         <div>Login Successful</div>
    );
};

export default LoginSuccess;
Enter fullscreen mode Exit fullscreen mode

2. Backend Server Setup (Node.js with Express):

const express = require('express');
const axios = require('axios');
const app = express();

const clientId = 'YOUR_GOOGLE_CLIENT_ID';
const clientSecret = 'YOUR_GOOGLE_CLIENT_SECRET'; // Replace with your actual client secret
const redirectUri = 'http://localhost:5000/callback';

app.get('/callback', async (req, res) => {
  const code = req.query.code;

  try {
    const response = await axios.post('https://oauth2.googleapis.com/token', {
      code,
      client_id: clientId,
      client_secret: clientSecret,
      redirect_uri: redirectUri,
      grant_type: 'authorization_code'
    });

    const tokens = response.data;
    res.redirect(`http://localhost:3000/auth/success?token=${tokens}`); // Replace with your success route if needed
  } catch (error) {
    console.error(error);
    res.status(500).send('Authentication failed');
  }
});


app.listen(5000, () => {
  console.log('Server running on http://localhost:5000');
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

This approach offers a smooth integration with Google's authentication services, making it valuable tool for enhancing user experience in your ReactJs applications. Feel free to explore additional features to further enrich your application's functionality.

This article was created by the assistance of Gemini and ChatGPT.

💖 💪 🙅 🚩
yusufginanjar
Yusuf Ginanjar

Posted on May 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related