Auth.js with SvelteKit

NextAuth is now framework agnostic, meaning it will work with SvelteKit! Here is a quick tutorial on getting up and running with it using the Github provider.

Setup

As usual create a fresh SvelteKit app with typescript.

npm create svelte@latest my-app
cd my-app
npm install
npm run dev

Now we need to install the new npm packages from Auth.js.

npm install @auth/core
npm install @auth/sveltekit

Hooks & Env Variables

Next we need to setup our handle hook.

You can think of hanlde hooks as middleware in SvelteKit. It is ran on every request, allows you to modify the header or body, and then return a response. In our case, we just need to add the Auth.js provider.

/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 })],
})