Files
archived-next-auth/apps/playground-sveltekit
dependabot[bot] a3b92dbaec chore(deps): bump jose from 4.5.0 to 4.9.3 in /apps/playground-sveltekit (#5359)
Bumps [jose](https://github.com/panva/jose) from 4.5.0 to 4.9.3.
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v4.5.0...v4.9.3)

---
updated-dependencies:
- dependency-name: jose
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-17 01:55:54 +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]/+server.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, options } from "$lib/next-auth"

export const { GET, POST } = NextAuth(options)

Add hook

import type { Handle } from "@sveltejs/kit"
import { getServerSession, options as nextAuthOptions } from "$lib/next-auth"

export const handle: Handle = async function handle({
  event,
  resolve,
}): Promise<Response> {
  const session = await getServerSession(event.request, nextAuthOptions)
  event.locals.session = session

  return resolve(event)
}

Load Session from Primary Layout

// src/lib/routes/+layout.server.ts
import type { LayoutServerLoad } from "./$types"

export const load: LayoutServerLoad = ({ locals }) => {
  return {
    session: locals.session,
  }
}

Protecting a Route

// src/lib/routes/protected/+page.ts
import { redirect } from "@sveltejs/kit"
import type { PageLoad } from "./$types"

export const load: PageLoad = async ({ parent }) => {
  const { session } = await parent()
  if (!session?.user) {
    throw redirect(302, "/")
  }
  return {}
}

Packaging lib

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