SvelteKit Tutorial

Tutorial: GitHub OAuth in SvelteKit

Before starting, make sure you've set up your database and middleware as described in the Getting started page.

Create an OAuth App

Create a GitHub OAuth app. Set the redirect URI to http://localhost:5173/login/github/callback. Copy and paste the client ID and secret to your .env file.

# .env
GITHUB_CLIENT_ID=""
GITHUB_CLIENT_SECRET=""

Update database

Add a github_id and username column to your user table.

column
type
attributes

github_id

number

unique

username

string

Create a DatabaseUserAttributes interface in the module declaration and add your database columns. By default, Lucia will not expose any database columns to the User type. To add a githubId and username field to it, use the getUserAttributes() option.

// src/lib/server/auth.ts
import { Authora } from "authora";
import { dev } from "$app/environment";
export const authora = new Authora(adapter, {
	sessionCookie: {
		attributes: {
			secure: !dev
		}
	},
	getUserAttributes: (attributes) => {
		return {
			// attributes has the type of DatabaseUserAttributes
			githubId: attributes.github_id,
			username: attributes.username
		};
	}
});

declare module "authora" {
	interface Register {
		Authora: typeof authora;
		DatabaseUserAttributes: DatabaseUserAttributes;
	}
}

interface DatabaseUserAttributes {
	github_id: number;
	username: string;
}

Setup Arctic

We recommend using Arctic for implementing OAuth. It is a lightweight library that provides APIs for creating authorization URLs, validating callbacks, and refreshing access tokens. This is the easiest way to implement OAuth with Lucia and it supports most major providers.

Initialize the GitHub provider with the client ID and secret.

Sign in page

Create routes/login/+page.svelte and add a basic sign in button, which should be a link to /login/github.

Create authorization URL

Create an API route in routes/login/github/+server.ts. Generate a new state, create a new authorization URL with createAuthorizationURL(), store the state, and redirect the user to the authorization URL. The user will be prompted to sign in with GitHub.

Validate callback

Create an API route in routes/login/github/callback/+server.ts to handle the callback. First, get the state from the cookie and the search params and compare them. Validate the authorization code in the search params with validateAuthorizationCode(). This will throw an OAuth2RequestError if the code or credentials are invalid. After validating the code, get the user's profile using the access token. Check if the user is already registered with the GitHub ID, and create a new user if they aren't. Finally, create a new session and set the session cookie.

Validate requests Without Middleware

You can validate requests by checking locals.user. The field user.username is available since we defined the getUserAttributes() option. You can protect pages, such as /, by redirecting unauthenticated users to the login page.

Validate requests With Middleware Included

To Be completed soon. in progress

More details on hooks https://kit.svelte.dev/docs/hooks https://kit.svelte.dev/docs/modules#sveltejs-kit-hooks

Sign out user !For Session Only

Sign out users by invalidating their session with Authora.invalidateSession(). Make sure to remove their session cookie by setting a blank session cookie created with Authora.createBlankSessionCookie().

Tutorial: Email and Password Auth in SvelteKit

Before starting, make sure you've set up your database and middleware as described in the Getting started page.

Update database

Add a username and password_hash column to your user table.

column
type
attributes

email

string

unique

password_hash

string

Create a DatabaseUserAttributes interface in the module declaration and add your database columns. By default, Lucia will not expose any database columns to the User type. To add a email field to it, use the getUserAttributes() option.

Sign up user

Create routes/signup/+page.svelte and set up a basic form.

Create a form action in routes/signup/+page.server.ts. First, do a very basic input validation. Hash the password, generate a new user ID, and create a new user. If successful, create a new session with Authora.createSession() and set a new session cookie.

For API SignUp

follow the above signup process, the only difference will be that you will return an object(json) instead of a redirect.

Argon2id should be your first choice for hashing passwords, followed by Scrypt and Bcrypt. Hashing is by definition computationally expensive so you should use the most performant option for your runtime.

  • For Node.js we recommend using @node-rs/argon2.

  • For Bun, we recommend using Bun.password.

  • Use Deno-specific packages for Deno.

  • For other runtimes (e.g. Cloudflare Workers), your choice is very limited. @noble/hashes provides pure-js implementations of various hashing algorithms, but because it's written in JS, you may hit into CPU limitations of your service. If possible, avoid these runtimes when you need to hash passwords.

Make sure to check the recommended minimum parameters for your hashing algorithm.

Sign in user

Create routes/login/+page.svelte and set up a basic form.

Create a form action in routes/login/+page.server.ts. First, do a very basic input validation. Get the user with the username and verify the password. If successful, create a new session with Authora.createSession() and set a new session cookie.

Validate requests Without Middleware -email

check the above solution

Sign out user -email

check the above solution

Last updated