Handling authorization · authjs.dev

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

Usage

Lazy initialization

supports lazy initialization where you can read the object to lazily set the configuration. This is especially useful when you have to get the environment variables from for platforms like Cloudflare Workers.

Re-export the handle in :

Remember to set the environment variable. This should be a minimum of 32 characters, random string. On UNIX systems you can use or check out .

When deploying your app outside Vercel, set the variable to 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:

Signing in and Signing out

Server-side

and are components that 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 and components to login and logout using SvelteKit’s server-side form actions. Another example is available on our svelte-auth-example repo.

You will need two things to make this work:

  1. Using the components in your SvelteKit app’s frontend (for instance )
  2. Add the required at (for ) and (for ) to handle the form actions

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

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

Client-Side

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

Managing the session

The above example checks for a session available in , 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 . The following code sets the session data in the store to be available to all routes.

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

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 file. Notice in this case that you could also and grab the session from there, however this implementation works even if you haven’t done the above in your root

You should NOT put authorization logic in a as the logic is not guaranteed to propagate to leafs in the tree. Prefer to manually protect each route through the 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 in your , is a function that is designed to receive ALL requests sent to your SvelteKit webapp. You should export it from and import it in your . To use multiple handles in your , we can use SvelteKit’s to execute all of them in series.

Now any routes under 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

  • If you build your SvelteKit application with enabled, pages which have an anchor tag to the default signin page (i.e. ) will have trouble building. Please use the builtin functions or components to sign in or out instead.

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 option.

Extends

Properties

cause?

Type declaration
err?
Overrides

type


CredentialsSignin

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

  1. The user is redirected to the signin page, with in the URL. 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

Properties

code

The error code that is set in the 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


Account

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

Extends

  • <>

Indexable

[: ]: |

Properties

access_token?

Inherited from

authorization_details?

Inherited from

expires_at?

Calculated value based on TokenEndpointResponse.expires_in.

It is the absolute timestamp (in seconds) when the TokenEndpointResponse.access_token expires.

This value can be used for implementing token rotation together with TokenEndpointResponse.refresh_token.

See

expires_in?

Inherited from

id_token?

Inherited from

provider

Provider’s id for this account. E.g. “google”. See the full list at https://authjs.dev/reference/core/providers

providerAccountId

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 callback.
  • email: The user’s email address.
  • credentials: returned from the callback

refresh_token?

Inherited from

scope?

Inherited from

token_type?

NOTE: because the value is case insensitive it is always returned lowercased

Inherited from

type

Provider’s type for this account

userId?

id of the user this account belongs to

See

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


DefaultSession

Extended by

Properties

expires

user?


Profile

The user info returned from your OAuth provider.

See

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

Indexable

[: ]:

Properties

address?

birthdate?

email?

email_verified?

family_name?

gender?

given_name?

id?

locale?

middle_name?

name?

nickname?

phone_number?

picture?

preferred_username?

profile?

sub?

updated_at?

website?

zoneinfo?


Session

The active session of the logged in user.

Extends

Properties

expires

Inherited from

.

user?

Inherited from

.


User

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

Extends

Properties

email?

Inherited from

.

id?

Inherited from

.

image?

Inherited from

.

name?

Inherited from

.


customFetch

It can be used to support corporate proxies, custom fetch libraries, cache discovery endpoints, add mocks for testing, logging, set custom headers/params for non-spec compliant providers, etc.

Example

See


SvelteKitAuth()

The main entry point to

Parameters

Returns

handle

signIn

signOut

See

https://sveltekit.authjs.dev


SvelteKitAuthConfig

Re-exports SvelteKitAuthConfig

webauthnactions

Auth.js © Better Auth Inc. -

2026

Read the original on authjs.dev ↗