mirror of
https://github.com/SrIzan10/next-auth.git
synced 2026-05-01 10:55:20 +00:00
* docs: add SvelteKit playground * docs: update readme * add svelte2tsx for packaging * remove header component in lib folder * reexport next-auth functions * remove as strings * format svelte files * update README * format files * add hook usage in readme * Update README.md Co-authored-by: Balázs Orbán <info@balazsorban.com> * Update README.md Additional info for sveltekit + nextauth.js experimental project Co-authored-by: Balázs Orbán <info@balazsorban.com> * Update global.d.ts Remove sample github client id and secret Co-authored-by: Balázs Orbán <info@balazsorban.com> * Update .env.example Co-authored-by: Balázs Orbán <info@balazsorban.com> * Update example route Co-authored-by: Balázs Orbán <info@balazsorban.com> * remove .npmrc * remove pnpm lockfile * move prettier config to package.json * reformat files * Add secret config Co-authored-by: Balázs Orbán <info@balazsorban.com> * remove packaging related lines and files * remove package command * Update next-auth.ts Co-authored-by: Balázs Orbán <info@balazsorban.com>
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>