Skip to main content

@auth/sveltekit

warning

@auth/sveltekit is currently experimental. The API might change.

SvelteKit Auth is the official SvelteKit integration for Auth.js. It provides a simple way to add authentication to your SvelteKit app in a few lines of code.

Installation​

npm install @auth/sveltekit

Usage​

src/auth.ts

import { SvelteKitAuth } from "@auth/sveltekit"
import GitHub from "@auth/sveltekit/providers/github"
import { GITHUB_ID, GITHUB_SECRET } from "$env/static/private"

export const { handle, signIn, signOut } = SvelteKitAuth({
providers: [GitHub({ clientId: GITHUB_ID, clientSecret: GITHUB_SECRET })],
})

or to use SvelteKit platform environment variables for platforms like Cloudflare

src/auth.ts
import { SvelteKitAuth } from "@auth/sveltekit"
import GitHub from "@auth/sveltekit/providers/github"
import type { Handle } from "@sveltejs/kit";

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

Re-export the handle in src/hooks.server.ts:

src/hooks.server.ts
export { handle } from "./auth"

Remember to set the AUTH_SECRET environment variable. This should be a minimum of 32 characters, random string. On UNIX systems you can use openssl rand -hex 32 or check out https://generate-secret.vercel.app/32.

When deploying your app outside Vercel, set the AUTH_TRUST_HOST variable to true for other hosting providers like Cloudflare Pages or Netlify.

The callback URL used by the providers must be set to the following, unless you override SvelteKitAuthConfig.basePath:

[origin]/auth/callback/[provider]

Signing in and Signing out​

Server-side​

<SignIn /> and <SignOut /> are components that @auth/sveltekit provides out of the box - they handle the sign-in/signout flow, and can be used as-is as a starting point or customized for your own components. This is an example of how to use the SignIn and SignOut components to login and logout using SvelteKit's server-side form actions. You will need two things to make this work:

  1. Using the components in your SvelteKit app's frontend
  2. Add the required page.server.ts at /signin (for SignIn) and /signout (for SignOut) to handle the form actions
<script>
import { SignIn, SignOut } from "@auth/sveltekit/components"
import { page } from "$app/stores"
</script>

<h1>SvelteKit Auth Example</h1>
<div>
{#if $page.data.session}
{#if $page.data.session.user?.image}
<img
src={$page.data.session.user.image}
class="avatar"
alt="User Avatar"
/>
{/if}
<span class="signedInText">
<small>Signed in as</small><br />
<strong>{$page.data.session.user?.name ?? "User"}</strong>
</span>
<SignOut>
<div slot="submitButton" class="buttonPrimary">Sign out</div>
</SignOut>
{:else}
<span class="notSignedInText">You are not signed in</span>
<SignIn>
<div slot="submitButton" class="buttonPrimary">Sign in</div>
</SignIn>
<SignIn provider="facebook"/>
{/if}
</div>

To set up the form actions, we need to define the files in src/routes:

src/routes/signin/+page.server.ts
import { signIn } from "../../auth"
import type { Actions } from "./$types"
export const actions: Actions = { default: signIn }
src/routes/signout/+page.server.ts
import { signOut } from "../../auth"
import type { Actions } from "./$types"
export const actions: Actions = { default: signOut }

These routes are customizeable with the signInPage and signOutPage props on the respective comopnents.

Client-Side​

We also export two methods from @auth/sveltekit/client in order to do client-side sign-in and sign-out actions.

src/routes/index.svelte
import { signIn, signOut } from "@auth/sveltekit/client"

<nav>
<p>
These actions are all using the methods exported from
<code>@auth/sveltekit/client</code>
</p>
<div class="actions">
<div class="wrapper-form">
<button on:click={() => signIn("github")}>Sign In with GitHub</button>
</div>
<div class="wrapper-form">
<button on:click={() => signIn("discord")}>Sign In with Discord</button>
</div>
<div class="wrapper-form">
<div class="input-wrapper">
<label for="password">Password</label>
<input
bind:value={password}
type="password"
id="password"
name="password"
required
/>
</div>
<button on:click={() => signIn("credentials", { password })}>
Sign In with Credentials
</button>
<button on:click={() => signOut()})}>
Sign Out
</button>
</div>
</div>
</nav>

Managing the session​

The above example checks for a session available in $page.data.session, however that needs to be set by us somewhere. If you want this data to be available to all your routes you can add this to src/routes/+layout.server.ts. The following code sets the session data in the $page store to be available to all routes.

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

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

What you return in the function LayoutServerLoad will be available inside the $page store, in the data property: $page.data. In this case we return an object with the 'session' property which is what we are accessing in the other code paths.

Handling authorization​

In SvelteKit there are a few ways you could protect routes from unauthenticated users.

Per component​

The simplest case is protecting a single page, in which case you should put the logic in the +page.server.ts file. Notice in this case that you could also await event.parent and grab the session from there, however this implementation works even if you haven't done the above in your root +layout.server.ts

import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async (event) => {
const session = await event.locals.auth();
if (!session?.user) throw redirect(303, '/auth');
return {};
};
danger

Make sure to ALWAYS grab the session information from the parent instead of using the store in the case of a PageLoad. Not doing so can lead to users being able to incorrectly access protected information in the case the +layout.server.ts does not run for that page load. This code sample already implements the correct method by using const { session } = await parent();. For more information on SvelteKit's load functionality behaviour and its implications on authentication, see this SvelteKit docs section.

You should NOT put authorization logic in a +layout.server.ts as the logic is not guaranteed to propagate to leafs in the tree. Prefer to manually protect each route through the +page.server.ts file to avoid mistakes. It is possible to force the layout file to run the load function on all routes, however that relies certain behaviours that can change and are not easily checked. For more information about these caveats make sure to read this issue in the SvelteKit repository: https://github.com/sveltejs/kit/issues/6315

Per path​

Another method that's possible for handling authorization is by restricting certain URIs from being available. For many projects this is better because:

  • This automatically protects actions and api routes in those URIs
  • No code duplication between components
  • Very easy to modify

The way to handle authorization through the URI is to override your handle hook. The handle hook, returned from SvelteKitAuth in your src/auth.ts, is a function that is designed to receive ALL requests sent to your SvelteKit webapp. You should export it from src/auth.ts and import it in your src/hooks.server.ts. To use multiple handles in your hooks.server.ts, we can use SvelteKit's sequence to execute all of them in series.

src/auth.ts
import { SvelteKitAuth } from '@auth/sveltekit';
import GitHub from '@auth/sveltekit/providers/github';

export const { handle, signIn, signOut } = SvelteKitAuth({
providers: [GitHub]
}),
src/hooks.server.ts
import { redirect, type Handle } from '@sveltejs/kit';
import { handle as authenticationHandle } from './auth';
import { sequence } from '@sveltejs/kit/hooks';

async function authorizationHandle({ event, resolve }) {
// Protect any routes under /authenticated
if (event.url.pathname.startsWith('/authenticated')) {
const session = await event.locals.auth();
if (!session) {
// Redirect to the signin page
throw redirect(303, '/auth/signin');
}
}

// If the request is still here, just proceed as normally
return resolve(event);
}

// First handle authentication, then authorization
// Each function acts as a middleware, receiving the request handle
// And returning a handle which gets passed to the next function
export const handle: Handle = sequence(authenticationHandle, authorizationHandle)
info

Learn more about SvelteKit's handle hooks and sequence here.

Now any routes under /authenticated will be transparently protected by the handle hook. You may add more middleware-like functions to the sequence and also implement more complex authorization business logic inside this file. This can also be used along with the component-based approach in case you need a specific page to be protected and doing it by URI could be faulty.

Notes​

info

Learn more about @auth/sveltekit here.

info

PRs to improve this documentation are welcome! See this file.

SvelteKitAuth()​

SvelteKitAuth(config): {
handle: Handle;
signIn: Action;
signOut: Action;
}

The main entry point to @auth/sveltekit

Parameters​

β–ͺ config: SvelteKitAuthConfig | (event) => PromiseLike< SvelteKitAuthConfig >

Returns​

object

handle​

handle: Handle;

signIn​

signIn: Action;

signOut​

signOut: Action;

See​

https://sveltekit.authjs.dev


Account​

Usually contains information about the provider being used and also extends TokenSet, which is different tokens returned by OAuth Providers.

Extends​

  • Partial< OpenIDTokenEndpointResponse >

Properties​

provider​

provider: string;

Provider's id for this account. Eg.: "google"

providerAccountId​

providerAccountId: string;

This value depends on the type of the provider being used to create the account.

  • oauth/oidc: The OAuth account's id, returned from the profile() callback.
  • email: The user's email address.
  • credentials: id returned from the authorize() callback

type​

type: ProviderType;

Provider's type for this account

expires_at​

expires_at?: number;

Calculated value based on [OAuth2TokenEndpointResponse.expires_in]([object Object]).

It is the absolute timestamp (in seconds) when the [OAuth2TokenEndpointResponse.access_token]([object Object]) expires.

This value can be used for implementing token rotation together with [OAuth2TokenEndpointResponse.refresh_token]([object Object]).

See​

userId​

userId?: string;

id of the user this account belongs to

See​

https://authjs.dev/reference/core/adapters#user


Profile​

The user info returned from your OAuth provider.

See​

https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims


Session​

The active session of the logged in user.

Extends​

  • DefaultSession

SvelteKitAuthConfig​

Configure the SvelteKitAuth method.

Extends​

  • Omit< AuthConfig, "raw" >

Properties​

providers​

providers: Provider[];

List of authentication providers for signing in (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order. This can be one of the built-in providers or an object with a custom provider.

Default​
[]
Inherited from​

Omit.providers

adapter​

adapter?: Adapter;

You can use the adapter option to pass in your database adapter.

Inherited from​

Omit.adapter

basePath​

basePath?: string;

The base path of the Auth.js API endpoints.

Default​
"/api/auth" in "next-auth"; "/auth" with all other frameworks
Inherited from​

Omit.basePath

callbacks​

callbacks?: Partial< CallbacksOptions< Profile, Account > >;

Callbacks are asynchronous functions you can use to control what happens when an action is performed. Callbacks are extremely powerful, especially in scenarios involving JSON Web Tokens as they allow you to implement access controls without a database and to integrate with external databases or APIs.

Inherited from​

Omit.callbacks

cookies​

cookies?: Partial< CookiesOptions >;

You can override the default cookie names and options for any of the cookies used by Auth.js. You can specify one or more cookies with custom properties and missing options will use the default values defined by Auth.js. If you use this feature, you will likely want to create conditional behavior to support setting different cookies policies in development and production builds, as you will be opting out of the built-in dynamic policy.

  • ⚠ This is an advanced option. Advanced options are passed the same way as basic options, but may have complex implications or side effects. You should try to avoid using advanced options unless you are very comfortable using them.
Default​
{}
Inherited from​

Omit.cookies

debug​

debug?: boolean;

Set debug to true to enable debug messages for authentication and database operations.

  • ⚠ If you added a custom [AuthConfig.logger]([object Object]), this setting is ignored.
Default​
false
Inherited from​

Omit.debug

events​

events?: Partial< EventCallbacks >;

Events are asynchronous functions that do not return a response, they are useful for audit logging. You can specify a handler for any of these events below - e.g. for debugging or to create an audit log. The content of the message object varies depending on the flow (e.g. OAuth or Email authentication flow, JWT or database sessions, etc), but typically contains a user object and/or contents of the JSON Web Token and other information relevant to the event.

Default​
{}
Inherited from​

Omit.events

experimental​

experimental?: {
enableWebAuthn: boolean;
};

Use this option to enable experimental features. When enabled, it will print a warning message to the console.

Note​

Experimental features are not guaranteed to be stable and may change or be removed without notice. Please use with caution.

Default​
{}
Type declaration​
enableWebAuthn​
enableWebAuthn?: boolean;

Enable WebAuthn support.

Default​
false
Inherited from​

Omit.experimental

jwt​

jwt?: Partial< JWTOptions >;

JSON Web Tokens are enabled by default if you have not specified an [AuthConfig.adapter]([object Object]). JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour.

Inherited from​

Omit.jwt

logger​

logger?: Partial< LoggerInstance >;

Override any of the logger levels (undefined levels will use the built-in logger), and intercept logs in NextAuth. You can use this option to send NextAuth logs to a third-party logging service.

Example​
// /auth.ts
import log from "logging-service"

export const { handlers, auth, signIn, signOut } = NextAuth({
logger: {
error(code, ...message) {
log.error(code, message)
},
warn(code, ...message) {
log.warn(code, message)
},
debug(code, ...message) {
log.debug(code, message)
}
}
})
  • ⚠ When set, the [AuthConfig.debug]([object Object]) option is ignored
Default​
console
Inherited from​

Omit.logger

pages​

pages?: Partial< PagesOptions >;

Specify URLs to be used if you want to create custom sign in, sign out and error pages. Pages specified will override the corresponding built-in page.

Default​
{}
Example​
  pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error',
verifyRequest: '/auth/verify-request',
newUser: '/auth/new-user'
}
Inherited from​

Omit.pages

redirectProxyUrl​

redirectProxyUrl?: string;

When set, during an OAuth sign-in flow, the redirect_uri of the authorization request will be set based on this value.

This is useful if your OAuth Provider only supports a single redirect_uri or you want to use OAuth on preview URLs (like Vercel), where you don't know the final deployment URL beforehand.

The url needs to include the full path up to where Auth.js is initialized.

Note​

This will auto-enable the state OAuth2Config.checks on the provider.

Example​
"https://authjs.example.com/api/auth"

You can also override this individually for each provider.

Example​
GitHub({
...
redirectProxyUrl: "https://github.example.com/api/auth"
})
Default​

AUTH_REDIRECT_PROXY_URL environment variable

See also: Guide: Securing a Preview Deployment

Inherited from​

Omit.redirectProxyUrl

secret​

secret?: string | string[];

A random string used to hash tokens, sign cookies and generate cryptographic keys.

To generate a random string, you can use the Auth.js CLI: npx auth secret

Note​

You can also pass an array of secrets, in which case the first secret that successfully decrypts the JWT will be used. This is useful for rotating secrets without invalidating existing sessions. The newer secret should be added to the start of the array, which will be used for all new sessions.

Inherited from​

Omit.secret

session​

session?: {
generateSessionToken: () => string;
maxAge: number;
strategy: "jwt" | "database";
updateAge: number;
};

Configure your session like if you want to use JWT or a database, how long until an idle session expires, or to throttle write operations in case you are using a database.

Type declaration​
generateSessionToken​
generateSessionToken?: () => string;

Generate a custom session token for database-based sessions. By default, a random UUID or string is generated depending on the Node.js version. However, you can specify your own custom string (such as CUID) to be used.

Returns​

string

Default​

randomUUID or randomBytes.toHex depending on the Node.js version

maxAge​
maxAge?: number;

Relative time from now in seconds when to expire the session

Default​
2592000 // 30 days
strategy​
strategy?: "jwt" | "database";

Choose how you want to save the user session. The default is "jwt", an encrypted JWT (JWE) in the session cookie.

If you use an adapter however, we default it to "database" instead. You can still force a JWT session by explicitly defining "jwt".

When using "database", the session cookie will only contain a sessionToken value, which is used to look up the session in the database.

Documentation | Adapter | About JSON Web Tokens

updateAge​
updateAge?: number;

How often the session should be updated in seconds. If set to 0, session is updated every time.

Default​
86400 // 1 day
Inherited from​

Omit.session

theme​

theme?: Theme;

Changes the theme of built-in [AuthConfig.pages]([object Object]).

Inherited from​

Omit.theme

trustHost​

trustHost?: boolean;

Auth.js relies on the incoming request's host header to function correctly. For this reason this property needs to be set to true.

Make sure that your deployment platform sets the host header safely.

note

Official Auth.js-based libraries will attempt to set this value automatically for some deployment platforms (eg.: Vercel) that are known to set the host header safely.

Inherited from​

Omit.trustHost

useSecureCookies​

useSecureCookies?: boolean;

When set to true then all cookies set by NextAuth.js will only be accessible from HTTPS URLs. This option defaults to false on URLs that start with http:// (e.g. http://localhost:3000) for developer convenience. You can manually set this option to false to disable this security feature and allow cookies to be accessible from non-secured URLs (this is not recommended).

  • ⚠ This is an advanced option. Advanced options are passed the same way as basic options, but may have complex implications or side effects. You should try to avoid using advanced options unless you are very comfortable using them.

The default is false HTTP and true for HTTPS sites.

Inherited from​

Omit.useSecureCookies


User​

The shape of the returned object in the OAuth providers' profile callback, available in the jwt and session callbacks, or the second parameter of the session callback, when using a database.


AuthError​

Base error class for all Auth.js errors. It's optimized to be printed in the server logs in a nicely formatted way via the logger.error option.

Extends​

  • Error

Properties​

type​

type: ErrorType;

The error type. Used to identify the error in the logs.


CredentialsSignin​

Can be thrown from the authorize callback of the Credentials provider. When an error occurs during the authorize callback, two things can happen:

  1. The user is redirected to the signin page, with error=CredentialsSignin&code=credentials in the URL. code is configurable.
  2. If you throw this error in a framework that handles form actions server-side, this error is thrown, instead of redirecting the user, so you'll need to handle.

Extends​

  • SignInError

Properties​

code​

code: string;

The error code that is set in the code query parameter of the redirect URL.

⚠ NOTE: This property is going to be included in the URL, so make sure it does not hint at sensitive errors.

The full error is always logged on the server, if you need to debug.

Generally, we don't recommend hinting specifically if the user had either a wrong username or password specifically, try rather something like "Invalid credentials".

type​

type: ErrorType;

The error type. Used to identify the error in the logs.

Inherited from​

SignInError.type