Google SSO hooks for react applications.
I needed SSO for google users and wasn't quite satisfied with what I found in the react eco system. Perhaps this will be useful for someone else, so here we go 🚀
The package exposes its own declaration files; you won't need to install any @types/* if you use typescript.
To install, use either yarn or npm:
yarn add gapi-oauth-react-hooks
npm i gapi-oauth-react-hooks
It's best to setup the config early, perhaps in the index or app file:
import { GapiConfig } from "gapi-oauth-react-hooks";
// pulling from .env here
GapiConfig.setup(
process.env.GOOGLE_AUTH_CLIENTID,
process.env.GOOGLE_AUTH_SCOPE,
process.env.GOOGLE_AUTH_REDIRECTURI
);
ReactDOM.render(<Login />, document.getElementById("root"));
Now, let's use the main hook in our Login component:
import { useGoogleAuth, UserProfile } from "gapi-oauth-react-hooks";
export const Login = () => {
const auth = useGoogleAuth();
const display = {
Errored: <>Oh no!</>,
Loading: <>Loading ...</>,
NotSignedIn: <button onClick={auth.onSignIn} >Login</button>,
SignedIn: <SignedIn {...auth} />
};
return <>{display[auth.state]}</>;
};
interface SignedInProps {
onSignOut: () => Promise<void>;
signedUser?: UserProfile;
authResponse?: gapi.auth2.AuthResponse;
}
const SignedIn: React.FC<SignedInProps> = ({ onSignOut, signedUser, authResponse }) => (
<>
<div>user {JSON.stringify(signedUser)}</div>
<div>auth response {JSON.stringify(authResponse)}</div>
<button onClick={onSignOut} >Logout</button>
</>
);
This package exposes two functions as well as two types:
This type defines gapi state.
Value | Description |
---|---|
Loading | gapi is not ready yet |
Errored | an error occured while loading gapi |
SignedIn | gapi is ready and a user is signed in |
NotSignedIn | gapi is ready and no user is signed in |
This type defines user data properties.
Property | Description |
---|---|
id | the id of the user |
the user email | |
familyName | the user family name |
givenName | the user given name |
name | the user name |
imageUrl | the user avatar |
This type defines what returns the useGoogleAuth
hook.
Property | Description |
---|---|
state | The gapi state |
signedUser | The signer user (duh) |
authResponse | The auth response |
onSignIn | A function initiating login |
onSignOut | A function initiating logout |
This static class contains a config function that takes three parameters. Once called, useGoogleAuth
can be used.
import { GapiConfig } from 'gapi-oauth-react-hooks';
GapiConfig.setup(clientId, scope, redirectUri);
Parameter | Description |
---|---|
clientId | The gapi client id |
scope | The requested scope |
redirectUri | The redirect Uri |
This react hook handles signin and signout using gapi auth2.
import { useGoogleAuth, GoogleAuthHookProps } from 'gapi-oauth-react-hooks';
const {
state,
signedUser,
authResponse,
onSignIn,
onSignOut,
}: GoogleAuthHookProps = useGoogleAuth();