In the modern web development landscape, creating a secure and efficient authentication and authorization service is crucial for any application. Supabase, an open-source Firebase alternative, offers robust backend services, including authentication. When combined with SvelteKit, a fast SSR (server-side rendering) framework, you can build a seamless and secure user experience. This guide will take you through the process of integrating Supabase authentication and authorization with a SvelteKit application.
Setting Up the Environment
Before we dive into coding, ensure you have the following prerequisites:
- Node.js installed.
- Basic understanding of Svelte and SvelteKit.
- A Supabase account and a project set up.
Let’s start by creating a new SvelteKit project:
npm init svelte@next my-auth-app
cd my-auth-app
npm install
Integrating Supabase
First, install the Supabase client library:
npm install @supabase/supabase-js
Create a supabaseClient.js
file in the src/lib
directory:
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY'
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
Replace YOUR_SUPABASE_URL
and YOUR_SUPABASE_ANON_KEY
with your project credentials from the Supabase dashboard.
Building the Authentication Service
Sign-Up and Sign-In
Create a Auth.svelte
component under src/routes
:
<script>
import { supabase } from '$lib/supabaseClient'
let email = ''
let password = ''
async function signUp() {
const { user, error } = await supabase.auth.signUp({ email, password })
if (error) console.error('Error signing up:', error)
else console.log('Sign up successful', user)
}
async function signIn() {
const { user, error } = await supabase.auth.signIn({ email, password })
if (error) console.error('Error signing in:', error)
else console.log('Sign in successful', user)
}
</script>
<input type="email" bind:value={email} placeholder="Email" />
<input type="password" bind:value={password} placeholder="Password" />
<button on:click={signUp}>Sign Up</button>
<button on:click={signIn}>Sign In</button>
This component provides basic sign-up and sign-in functionality.
User Session Handling
Create a UserSession.svelte
component to handle user sessions:
<script>
import { supabase } from '$lib/supabaseClient'
import { onMount } from 'svelte'
let user
onMount(async () => {
user = supabase.auth.session()?.user || null
supabase.auth.onAuthStateChange((_event, session) => {
user = session?.user || null
})
})
async function signOut() {
await supabase.auth.signOut()
user = null
}
</script>
{#if user}
<div>
<h2>Hello, {user.email}</h2>
<button on:click={signOut}>Sign out</button>
</div>
{:else}
<p>Please sign in.</p>
{/if}
This component listens for changes in the authentication state and updates the user session accordingly.
Authorization and Protected Routes
SvelteKit uses file-based routing. To protect a route, you can check if a user is authenticated and redirect if not. Create a src/routes/protected.svelte
:
<script context="module">
import { supabase } from '$lib/supabaseClient'
export async function load({ fetch }) {
const user = supabase.auth.session()?.user
if (!user) {
return {
status: 302,
redirect: '/login'
}
}
return {}
}
</script>
<h1>Protected Page</h1>
<p>Only logged-in users can see this page.</p>
You’ve now set up a basic authentication and authorization service using Supabase and SvelteKit. This setup provides a solid foundation for any web application requiring user authentication. You can extend it with more features like password reset, third-party logins, and user role management as per your project’s needs.