Skip to content

Instantly share code, notes, and snippets.

@koutyuke
Forked from sonipranjal/google-sign-in.tsx
Created December 15, 2023 02:59
Show Gist options
  • Select an option

  • Save koutyuke/5011b70a172990faf8547008af6e1e37 to your computer and use it in GitHub Desktop.

Select an option

Save koutyuke/5011b70a172990faf8547008af6e1e37 to your computer and use it in GitHub Desktop.
Supabase + Expo + Google Sign In
// go to supabase dashboard -> into auth -> url config -> put the Redirect URLs as [your-scheme]://google-auth
import * as WebBrowser from "expo-web-browser";
WebBrowser.maybeCompleteAuthSession();
const extractParamsFromUrl = (url: string) => {
const parsedUrl = new URL(url);
const params = parsedUrl.searchParams; // Using searchParams instead of splitting on "#"
const data = {
access_token: params.get("access_token"),
expires_in: parseInt(params.get("expires_in") || "0"),
refresh_token: params.get("refresh_token"),
token_type: params.get("token_type"),
provider_token: params.get("provider_token"),
code: params.get("code"),
};
return data;
};
// to warm up the browser
useEffect(() => {
WebBrowser.warmUpAsync();
return () => {
WebBrowser.coolDownAsync();
};
}, []);
//button
<Button
onPress={async () => {
const res = await supabase.auth.signInWithOAuth({
provider: "google",
options: {
redirectTo: "[your-scheme]://google-auth",
queryParams: {
prompt: "consent",
},
},
});
const googleOAuthUrl = res.data.url;
if (!googleOAuthUrl) return Alert.alert("no oauth url found!");
const result = await WebBrowser.openAuthSessionAsync(
googleOAuthUrl,
"[your-scheme]://google-auth?",
{
showInRecents: true,
},
).catch((err) => {
console.log(err);
});
if (result && result.type === "success") {
const params = extractParamsFromUrl(result.url);
if (params.code) {
const user = await supabase.auth.exchangeCodeForSession(
params.code,
);
console.log(user);
return;
} else {
// sign in/up failed
}
} else {
console.log("handle failed error");
}
}}
title="Sign in with google"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment