Skip to main content

Module: main

danger

@auth/sveltekit is currently experimental. The API will change in the future.

SvelteKit Auth is the official SvelteKit integration for Auth.js. It provides a simple way to add authentication to your SvelteKit app in a few lines of code.

Installation​

npm install @auth/core @auth/sveltekit

Usage​

src/hooks.server.ts
import SvelteKitAuth from "@auth/sveltekit"
import GitHub from "@auth/core/providers/github"
import { GITHUB_ID, GITHUB_SECRET } from "$env/static/private"

export const handle = SvelteKitAuth({
providers: [GitHub({ clientId: GITHUB_ID, clientSecret: GITHUB_SECRET })],
})

Don't forget to set the AUTH_SECRET environment variable. This should be a random 32 character string. On unix systems you can use openssl rand -hex 32 or check out https://generate-secret.vercel.app/32.

When deploying your app outside Vercel, set the AUTH_TRUST_HOST variable to true for other hosting providers like Cloudflare Pages or Netlify.

The callback URL used by the providers must be set to the following, unless you override prefix:

[origin]/auth/callback/[provider]

Signing in and signing out​

<script>
import { signIn, signOut } from "@auth/sveltekit/client"
import { page } from "$app/stores"
</script>

<h1>SvelteKit Auth Example</h1>
<p>
{#if $page.data.session}
{#if $page.data.session.user?.image}
<span
style="background-image: url('{$page.data.session.user.image}')"
class="avatar"
/>
{/if}
<span class="signedInText">
<small>Signed in as</small><br />
<strong>{$page.data.session.user?.name ?? "User"}</strong>
</span>
<button on:click={() => signOut()} class="button">Sign out</button>
{:else}
<span class="notSignedInText">You are not signed in</span>
<button on:click={() => signIn("github")}>Sign In with GitHub</button>
{/if}
</p>

Notes​

info

Learn more about @auth/sveltekit here.

info

PRs to improve this documentation are welcome! See this file.

Functions​

Interfaces​