DEV Community

Yuya Uzu
Yuya Uzu

Posted on

Migrate to New Google Identity Service (with React & NodeJS)

Here is the code sample of signing up users with the new Google Identity Service (GSI) using React & NodeJS.

Official Migration Guide: Link

1. Packages used

@react-oauth/google
google-auth-library

2. Client side code

Wrap your top component with the Provider and give your Google Client ID to it.

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

export const TopComponent = () => {
  return (
    <GoogleOAuthProvider clientId={GAPI_CLIENT_ID}>
      <YourApp />
    </GoogleOAuthProvider>
  )
}

Enter fullscreen mode Exit fullscreen mode

Make a login function to retrieve the "code".

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

// make a login function
const loginWitnGoogle = useGoogleLogin({
    onSuccess: (codeResponse) => {
      functionToSendToServer(codeResponse.code);
    },
    flow: "auth-code",
    ux_mode: "popup",
});

// attach the login function to the button
export const LoginPage = () => {
  return (
    <LoginButton onClick={loginWithGoogle}>Login with Google</LoginButton>
  )
}
Enter fullscreen mode Exit fullscreen mode

3. Backend code

Use the client generated "code" to retrieve id_token. Then use id_token to get the user profile data (email, picture, etc).

import { OAuth2Client } from "google-auth-library";

const oAuth2Client = new OAuth2Client(
  process.env.GAPI_CLIENT_ID,
  process.env.GAPI_CLIENT_SECRET,
  "postmessage"
);

// use the "code" to get user info from Google
async function getUserInfo(code) {
  const { tokens } = await oAuth2Client.getToken(code);

  const ticket = await oAuth2Client.verifyIdToken({
      idToken: tokens.id_token,
      audience: process.env.GAPI_CLIENT_ID
  });

  const payload = ticket.getPayload();

  return {
      email: payload.email,
      googleId: payload.sub,
      picture: payload.picture,
      name: payload.name,
  };
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)