Setting up Server-Side Auth for SvelteKit
Set up Server-Side Auth to use cookie-based authentication with SvelteKit.
Install Supabase packages
Install the @supabase/supabase-js
package and the helper @supabase/ssr
package.
_10npm install @supabase/supabase-js @supabase/ssr
Set up environment variables
Create a .env.local
file in your project root directory.
Fill in your PUBLIC_SUPABASE_URL
and PUBLIC_SUPABASE_ANON_KEY
:
Project URL
Anon key
Set up server-side hooks
Set up server-side hooks in src/hooks.server.ts
. The hooks:
- Create a request-specific Supabase client, using the user credentials from the request cookie. This client is used for server-only code.
- Check user authentication.
- Guard protected pages.
Create TypeScript definitions
To prevent TypeScript errors, add type definitions for the new event.locals
properties.
Create a Supabase client in your root layout
Create a Supabase client in your root +layout.ts
. This client can be used to access Supabase from the client or the server. In order to get access to the Auth token on the server, use a +layout.server.ts
file to pass in the session from event.locals
.
Listen to Auth events
Set up a listener for Auth events on the client, to handle session refreshes and signouts.
Create your first page
Create your first page. This example page calls Supabase from the server to get a list of countries from the database.
This is an example of a public page that uses publicly readable data.
To populate your database, run the countries quickstart from your dashboard.
Change the Auth confirmation path
If you have email confirmation turned on (the default), a new user will receive an email confirmation after signing up.
Change the email template to support a server-side authentication flow.
Go to the Auth templates page in your dashboard. In the Confirm signup
template, change {{ .ConfirmationURL }}
to {{ .SiteURL }}/api/auth/confirm?token_hash={{ .TokenHash }}&type=signup
.
Create a login page
Next, create a login page to let users sign up and log in.
Create the signup confirmation route
Finish the signup flow by creating the API route to handle email verification.
Create private routes
Create private routes that can only be accessed by authenticated users. The routes in the private
directory are protected by the route guard in hooks.server.ts
.
To ensure that hooks.server.ts
runs for every nested path, put a +layout.server.ts
file in the private
directory. This file can be empty, but must exist to protect routes that don't have their own +layout|page.server.ts
.