Auth in Sveltekit through Github

Using auth.js to set up a Github auth flow inside Sveltekit.

1. Install auth.js in sveltekit

npm install @auth/sveltekit

2. Set up Github OAuth app

3. Set up Hooks

  • create hooks.server.ts in the src directory and add below code:
import { SvelteKitAuth } from "@auth/sveltekit"
import GitHub from "@auth/core/providers/github"
import type { Handle } from "@sveltejs/kit";
import { GITHUB_ID, GITHUB_SECRET, AUTH_SECRET } from "$env/static/private"

export const handle = SvelteKitAuth(async() => {
  const authOptions = {
    providers: [GitHub({ clientId: GITHUB_ID, clientSecret: GITHUB_SECRET })],
    secret: AUTH_SECRET,
    trustHost: true
  }
  return authOptions
}) satisfies Handle;

4. Create root +layout.server.ts file and add code:

import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async (event) => {
  return {
    session: await event.locals.getSession()
  };
};

5. Now in the root +layout.svelte file, we need to do the following:

  • in the script tag:
import { page } from '$app/stores'
import { signIn, signOut } from '@auth/sveltekit/client'

6. Login/logout Buttons

anywhere in the layout.svelte file, add these 2 buttons:

  {#if $page.data.session?.user}
  <button class="blank" on:click={() => signOut}>Logout</button>
  {:else}
  <button class="blank" on:click={() => signIn('github')}>Login</button>
  {/if}

and your’re all set!