You can use jwt-decode
library to decode your credential OAuth Login, here is the step by step how to use it
- Install
jwt-decode
You can use npm install jwt-decode
or yarn add jwt-decode
or pnpm install jwt-decode
- Import
jwt-decode
to your App
import { GoogleLogin } from '@react-oauth/google';
import jwtDecode from 'jwt-decode'
...
<GoogleLogin
onSuccess = {credentialResponse => {
if (credentialResponse.credential != null) {
const USER_CREDENTIAL = jwtDecode(credentialResponse.credential);
console.log(USER_CREDENTIAL);
}
}
}
...
I use GoogleLoginOAuth from @react-oauth/google
, at my case this code it's work!
One more thing, ** just intermezzo ** if you use TypeScript, then you want destructure object to get name
or family_name
for instance
const { given_name, family_name } = USER_CREDENTIAL;
and then you get this error squiggles like this
Property 'family_name' does not exist on type 'unknown'
You can make type like this, copy it if you need it anyway
dataCredential.ts
export type dataCredential = {
aud: string,
azp: string,
email: string,
email_verified: boolean,
exp: number,
family_name: string,
given_name: string,
iss: string,
jti: string,
name: string,
nbf: number,
picture: string,
sub: string
}
and than you can make your code like this
import { GoogleLogin } from '@react-oauth/google';
import jwtDecode from 'jwt-decode'
import {dataCredential} from "../types/dataCredential";
...
<GoogleLogin
onSuccess = {credentialResponse => {
if (credentialResponse.credential != null) {
const USER_CREDENTIAL: dataCredential = jwtDecode(credentialResponse.credential);
console.log(USER_CREDENTIAL);
const { given_name, family_name } = USER_CREDENTIAL;
console.log(given_name, family_name)
}
}
}
...
Hope it helps!