Search code examples
next.jsgoogle-oauth

Next Js Google Auth


I am new to frontend development and currently trying to implement Google login in my login. I want my frontend to send google token to my backend when i click on login with google.

When this Button is clicked, I don't know how but in my frontend i want to send the google token to my backend to validate.

  <a className={styles.continue_with_email} href="">
        Continue With Email
      </a>

Is this possible? I am sorry if you did not get my question.


Solution

    1. install google oauth package

    npm install @react-oauth/google@latest

    1. Get your Google API client ID (here)

    2. Configure your OAuth Consent Screen (here)

    3. Wrap your application with GoogleOAuthProvider and create the button.

    import { GoogleOAuthProvider, GoogleLogin } from "@react-oauth/google";
    
    export default function LoginByGoogleComponent() {
      const handleLogin = (credentialResponse) => {
        // this contains the response from google you can get the token from here
        console.log(credentialResponse);
      };
    
      const handleLoginError = (err) => {
        console.log("Login Failed");
      };
    
      return (
        <GoogleOAuthProvider clientId="<your_client_id>">
          <GoogleLogin onSuccess={handleLogin} onError={handleLoginError} />
        </GoogleOAuthProvider>
      );
    }
    

    or if you want to use a custom button

    import { useGoogleLogin } from '@react-oauth/google';
    
    const login = useGoogleLogin({
      onSuccess: tokenResponse => console.log(tokenResponse),
    });
    
    <button onClick={() => login()}>Sign in with Google 🚀</button>;
    

    checkout the google oauth button package readme for more info here https://www.npmjs.com/package/@react-oauth/google