Files
archived-next-auth/apps/playground-sveltekit
dependabot[bot] 5081d25f5c chore(deps): bump next-auth in /apps/playground-sveltekit (#4859)
Bumps [next-auth](https://github.com/nextauthjs/next-auth) from 4.5.0 to 4.9.0.
- [Release notes](https://github.com/nextauthjs/next-auth/releases)
- [Changelog](https://github.com/nextauthjs/next-auth/blob/main/CHANGELOG.md)
- [Commits](https://github.com/nextauthjs/next-auth/compare/next-auth@v4.5.0...next-auth@v4.9.0)

---
updated-dependencies:
- dependency-name: next-auth
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-07 00:34:27 +02:00
..
2022-06-24 14:11:39 +02:00

SvelteKit + NextAuth.js Playground

NextAuth.js is committed to bringing easy authentication to other frameworks. https://github.com/nextauthjs/next-auth/issues/2294

SvelteKit support with NextAuth.js is currently experimental. This directory contains a minimal, proof-of-concept application. Parts of this is expected to be abstracted away into a package like @next-auth/sveltekit

Existing Project

Add API route

To add NextAuth.js to a project create a file called [...nextauth].js in routes/api/auth. This contains the dynamic route handler for NextAuth.js which will also contain all of your global NextAuth.js configurations.

import NextAuth from "$lib"
import GithubProvider from "next-auth/providers/github"

const nextAuthOptions = {
  // Configure one or more authentication providers
  providers: [
    GithubProvider({
      clientId: import.meta.env.VITE_GITHUB_CLIENT_ID,
      clientSecret: import.meta.env.VITE_GITHUB_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
}

export const { get, post } = NextAuth(nextAuthOptions)

Add hook

import { getServerSession } from "$lib"
import GithubProvider from "next-auth/providers/github"

const nextAuthOptions = {
  providers: [
    GithubProvider({
      clientId: import.meta.env.VITE_GITHUB_CLIENT_ID,
      clientSecret: import.meta.env.VITE_GITHUB_CLIENT_SECRET,
    }),
  ],
}

export async function handle({ event, resolve }) {
  const session = await getServerSession(event.request, nextAuthOptions)
  event.locals.session = session

  return resolve(event)
}

export function getSession(event) {
  return event.locals.session || {}
}

Protecting a route

<script context="module">
  export async function load({ session }) {
    const { user } = session

    if (!user) {
      return {
        status: 302,
        redirect: "/",
      }
    }

    return {
      props: {
        session,
      },
    }
  }
</script>

<script>
  export let session
</script>

<p>Session expiry: {session.expires}</p>

Packaging lib

Refer to https://kit.svelte.dev/docs/packaging