Google APIs setup

To set up a callback URL in a React application for Google APIs, follow these steps:

Step 1: Set up Google API credentials

  1. Go to the Google Cloud Console.
  2. Create a new project (or use an existing one).
  3. Navigate to APIs & Services > Credentials.
  4. Under OAuth 2.0 Client IDs, click Create Credentials.
  5. Select Web Application as the application type.
  6. Under Authorized JavaScript origins, add the domain or localhost (if developing locally) of your app (e.g., http://localhost:3000).
  7. Under Authorized redirect URIs, add your callback URL, which will be something like http://localhost:3000/auth/callback for local development or your production URL (e.g., https://yourapp.com/auth/callback).
  8. Save the client ID and client secret provided after the creation.

Step 2: Install Required Libraries in React

You need libraries to handle OAuth flow and Google API authentication.

npm install react-oauth/google

This is the easiest way to integrate Google Login into your React app.

Step 3: Set up Google OAuth in React

  1. In your React app, you can now use the GoogleOAuthProvider to wrap your app and configure the client ID.

App.js:

import React from "react";
import { GoogleOAuthProvider } from "@react-oauth/google";
import GoogleLoginButton from "./GoogleLoginButton"; // Create this component

const App = () => {
  return (
    <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID">
      <div className="App">
        <h1>React Google OAuth Example</h1>
        <GoogleLoginButton />
      </div>
    </GoogleOAuthProvider>
  );
};

export default App;
  1. Create a GoogleLoginButton component for handling Google login.

GoogleLoginButton.js:

import React from "react";
import { GoogleLogin } from "@react-oauth/google";
import { useNavigate } from "react-router-dom"; // Used for redirect

const GoogleLoginButton = () => {
  const navigate = useNavigate();

  const handleLoginSuccess = (response) => {
    // Store the token in your state or localStorage if needed
    console.log("Google login successful:", response);
    
    // Redirect to your callback route
    navigate("/auth/callback", { state: { token: response.credential } });
  };

  const handleLoginFailure = (error) => {
    console.log("Google login failed:", error);
  };

  return (
    <GoogleLogin
      onSuccess={handleLoginSuccess}
      onError={handleLoginFailure}
    />
  );
};

export default GoogleLoginButton;

Step 4: Create the Callback Component

This component will handle the callback URL and process the OAuth token.

AuthCallback.js:

import React, { useEffect } from "react";
import { useLocation } from "react-router-dom";

const AuthCallback = () => {
  const location = useLocation();

  useEffect(() => {
    if (location.state && location.state.token) {
      const token = location.state.token;
      console.log("Authenticated token received:", token);

      // You can now use this token to fetch Google API data or store it for later
    }
  }, [location]);

  return (
    <div>
      <h2>Google Authentication Callback</h2>
      <p>Authentication successful. You can now access your Google data.</p>
    </div>
  );
};

export default AuthCallback;

Step 5: Set up Routing

In your App.js, configure routes to handle the /auth/callback URL.

import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import GoogleLoginButton from "./GoogleLoginButton";
import AuthCallback from "./AuthCallback";

const App = () => {
  return (
    <Router>
      <div className="App">
        <h1>React Google OAuth Example</h1>
        <Routes>
          <Route path="/" element={<GoogleLoginButton />} />
          <Route path="/auth/callback" element={<AuthCallback />} />
        </Routes>
      </div>
    </Router>
  );
};

export default App;

Step 6: Test the Flow

  1. Start your React app.
  2. When you click the “Login with Google” button, you will be redirected to the Google login screen.
  3. After successful login, Google will redirect you to the callback URL (/auth/callback) with the authentication token.

You can now use this token to make requests to Google APIs (like accessing user profile information, etc.).

Summary

  • The callback URL (/auth/callback) handles the Google OAuth redirect.
  • Use the react-oauth/google library to simplify the OAuth flow.
  • Store the OAuth token upon successful login for further API requests.

Let me know if you need help with anything else!

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *