Google OAuth Implementation in Next Js

  • Implementing Google OAuth in a React JS application using the `@react-oauth/google` npm package involves a few straightforward steps. Below is a guide on how to set it up:
Step 1: Create Google OAuth Credentials
  • Create a new project or select an existing one.
  • Navigate to the "Credentials" tab on the left menu.
  • Click "Create credentials" and select "OAuth client ID".
  • Choose "Web application" as the application type.
  • Add your application's URI to "Authorized JavaScript origins" and the redirect URI (if applicable) to "Authorized redirect URIs". For local development, this is usually `http://localhost:3000`.
  • Click "Create" to generate your credentials. You will get a client ID, which will be used in your React application.
Step 2: Install the `@react-oauth/google` Package
  • In your React project directory, run the following command to install the `@react-oauth/google` package:


    npm install @react-oauth/google

Step 3: Initialize Google OAuth in Your React App
  • In your main application file (e.g., `App.js` or `index.js`), import and initialize the Google OAuth provider:

    import React from 'react';
    import { GoogleOAuthProvider } from '@react-oauth/google';

    // Your main App component or similar
    function App() {
        return (
            <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID">
                {/* Rest of your app components */}
            </GoogleOAuthProvider>
        );
    }

    export default App;

  • Replace `"YOUR_GOOGLE_CLIENT_ID"` with the actual client ID you obtained from the Google Developer Console.
Step 4: Implement the Google Login Button
  • In the component where you want to place the Google login button, use the `GoogleLogin` component:

    import React from 'react';
    import { GoogleLogin } from '@react-oauth/google';

    function Login() {
        const handleGoogleLogin = (response) => {
            console.log(response); // Handle the response object
        };

        return (
            <div>
                <GoogleLogin
                    onSuccess={handleGoogleLogin}
                    onError={() => console.log('Login Failed')}
                />
            </div>
        );
    }

    export default Login;


Another way to implement Step 4

Step 4: Implement Google Login Using `useGoogleLogin`
  • Instead of using a `GoogleLogin` component, you can use the `useGoogleLogin` hook to create a custom login button and manage the login process. Here’s how you can do it:

    import React from 'react';
    import { useGoogleLogin } from '@react-oauth/google';

    function Login() {

        async function fetchGoogleUserInfo(accessToken: string) {
            const res = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
                method: 'GET',
                headers: {
                    Authorization: `Bearer ${accessToken}`,
                },
            });

            if (!res.ok) {
                throw new Error('Failed to fetch user info');
            }

            const userInfo = await res.json();
            return userInfo;
        }

        const googleLogin = useGoogleLogin({
            onSuccess: async (tokenResponse) => {
                console.log(tokenResponse); // Token response from Google

                try {
                    const userInfo = await fetchGoogleUserInfo(tokenResponse.access_token);
                    console.log(userInfo); // User info object
                    // Here, you can handle the user's information, e.g., display it on the UI
                    // or store it in your app's state/context
                } catch (error) {
                    console.error('Error fetching user info:', error);
                }
            },
            onError: () => console.log('Login Failed'),
            // Optionally, specify the scopes you need
            scope: 'profile email'
        });

        return (
            <div>
                <button onClick={() => googleLogin()}>
                    Login with Google
                </button>
            </div>
        );
    }

    export default Login;

  • In this example, `useGoogleLogin` is a hook that takes an options object where you can specify `onSuccess` and `onError` callbacks. `onSuccess` is called with the token response from Google upon a successful login, and `onError` is called if the login process fails.
  • onSuccess: A callback function that is invoked when the login is successful. It receives the token response from Google.
  • onError: A callback function that is invoked when there is an error in the login process.
  • scope: (Optional) A space-delimited string that specifies the scopes for the access token. You can request access to user information, such as their profile or email. By default, it requests access to the user's profile.
  • Then, you create a button (or any clickable element) in your component's return statement. When this button is clicked, it triggers the `googleLogin` function to start the login process.
  • This approach gives you more control over the styling and placement of your login button and allows you to integrate the login functionality more seamlessly into your application's UI.
Step 5: Run Your Application

  • Run your React application. You should see a Google login button, and upon clicking it, you'll be prompted to log in with a Google account. After a successful login, the `handleGoogleLogin` function will be triggered with the response object, which contains the user's information and tokens.
  • This basic implementation should get you started with integrating Google OAuth into your React application. You can further customize the login flow and handle user data according to your application's needs.

No comments:

Post a Comment