Skip to content

Instantly share code, notes, and snippets.

@rogadev
Last active February 2, 2023 19:23
Show Gist options
  • Save rogadev/5ef318c54bc81c95c0909ae4165d9e52 to your computer and use it in GitHub Desktop.
Save rogadev/5ef318c54bc81c95c0909ae4165d9e52 to your computer and use it in GitHub Desktop.
Default Form Submission Problem (SvelteKit)
import { fail, redirect } from "@sveltejs/kit";
import type { Actions } from "./$types";
import type { AuthError, Provider } from "@supabase/supabase-js";
import supabase from "$lib/db";
export const actions: Actions = {
login: async (event) => {
const provider = event.url.searchParams.get("provider") as Provider;
// No provider means we're using the email/password in the body to log in.
if (!provider) {
const { email, password } = event.body;
const { error } = await supabase.auth.signInWithPassword({ email, password }) as AuthError;
// Error short cct.
if (error) {
if (error instanceof AuthError) {
console.error(`Error logging in with Supabase. Email: ${email}. Error: ${error.message}`);
return fail(error.status, error.message);
}
return fail(400, "Something went wrong");
}
// Otherwise, we've logged in successfully - redirect to dashboard.
return redirect(303, "/dashboard");
}
// If we have a provider, we're using OAuth to log in.
const { data: { url }, error } = await supabase.auth.signInWithOAuth({ provider, options: { redirectTo: `${event.url.origin}/dashboard` } });
if (error) {
if (error instanceof AuthError) {
console.error(`Error logging in with Supabase. Error: ${error.message}`);
return fail(error.status, error.message);
}
return fail(400, "Something went wrong");
}
throw redirect(303, url);
},
};
<script lang="ts">
import { page } from '$app/stores';
import Auth from './Auth.svelte';
$: session = $page.data.session;
</script>
{#if session}
<Auth />
{/if}
<form method="POST">
<button formaction="?/login&provider=google">Google</button>
<input type="email" name="email" />
<button formaction="?/login">Email</button>
</post>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment