Okupter

Handling authentication and authorization with JWT in SvelteKit

Justin's profile pic

Justin Ahinon

Last updated on

SvelteKit version: 1.0.0-next.572

GitHub repository: https://github.com/JustinyAhin/sveltekit-auth-jwt

SvelteKit is a meta-framework on top of Svelte for building web applications. It comes with a handful of features that make it delightful to work with. Things like load functions, API routes, server functions, form actions and progressive enhancement provide a full-fledged experience for end to end web applications development.

I have been using SvelteKit for quite some time now and at some point, I’ve struggled with finding a consistent way to handle all the authentication and authorization flow. Because I’ve not implemented such a thing in a JavaScript context before.

After a handful of trials, reading various repositories code and tutorials, I’ve come up with an implementation that seems satisfying for me and that I’m going to share in this article.

How does SvelteKit handles server side code?

In SvelteKit, you have two main ways to run server side code: API routes (or endpoints, as they officially called in the documentation) and server functions. Server functions are created in +page.server.ts or +layout.server.ts files or their JS equivalents.

Endpoints are JavaScript or TypeScript files that export regular HTTP methods. They take a request event in parameter and return a Response object.

Server functions can either be load functions or form actions. load functions run both during server side and client side rendering, while form actions are triggered as a result of a form submission.

In this tutorial, we’ll create a small project with a sign-up, login and guarded pages. Our authentication and authorization login are going to be implemented in our routes' server side code, and we will use SvelteKit hooks to authorize users in the guarded routes.

We will use JSON Web Tokens (JWT) to generate and verify encrypted tokens that will be sent along with all authenticated requests. We will also use a SQLite database as our store and Prisma to interact with it.

Creating the project

The final code for this tutorial is available on my GitHub here.

It’s pretty straightforward to create a SvelteKit project, by running the following command:

BASH

I’m using the skeleton template with TypeScript, Prettier and ESLint enabled.

Installing necessary dependencies

We will need a few dependencies that will be used along the way. First, we install prisma as a development dependency:

BASH

Now we will install bcryptjs to hash and compare passwords, jwt to generate and verify tokens, and @prisma/client to interact with our database:

BASH

When using TypeScript, some dependencies require type definitions. We install them with the following command:

BASH

Setting up the database

Let’s now use Prisma, to initialize a SQLite database and create a User model.

BASH

In our schema.prisma file, we will create a simple User model with an email and password fields.

JAVASCRIPT

We can generate the Prisma client and apply our schema changes to the database by running

BASH

How does JWT works?

JWT is basically a standard to securely transmit information between parties (in our case, a client and a server) as a JSON object. This information can be verified and trusted because it is digitally signed using a secret or a public/private key pair.

In an authentication-authorization flow, after a user successfully logs in, the server generates a JWT that contains some user’s information and sends it back to the client. The client then stores this token in a cookie or local storage and sends it along with every request to the server; which can then verify the token and grant access to protected resources/information.

Here is a simple diagram of how JWT works:

JWT auth flow

Authentication pages for our app

Now that we have a basic understanding of how JWT works, let’s create our authentication pages.

Sign up

The signup page HTML markup is pretty straightforward. It’s simply a form with an email and password input, and a submit button.

SVELTE

Here, we add method="post" to our form for posting signup data. But how are we going to handle that?

This is where SvelteKit form actions come in handy. In a +page.server.ts file, we can export some actions, allowing us to post data through a form. Here is what it looks like:

TYPESCRIPT

The default action for a form is called default . We could also use named actions in case we have many actions on a page.

What we are doing here is validating the data we get from the form, create a new user, return a validation error in case there's an error, and finally redirecting to the login page if everything is successful.

The code for creating a user can be found here.

In the current state, the signup form works without client side JavaScript. SvelteKit allows making the experience smoother with progressive enhancement. We do that by adding the use:enhance argument to our form element.

With that added, the form will be submitted with client side JavaScript, making it a better user experience.

SVELTE

Let's also add a few things to make the experience even better. We can display the validation error we returned in our server code on the frontend.

When we return something from a form action, it comes to the frontend as ActionData . We will use that to conditionally errors messages like this:

SVELTE

Note that we are using export let form: ActionData here. The form contains the data. For this to work, it needs to be named form .

Now, we can have this alert when there is an error:

Form error in the frontend

Login

The process for logging in is a bit similar with signing in. We use a form action to authenticate our user, and redirect to the guarded page. The main difference resides in setting up the JWT token as a cookie.

Let's see how it goes:

SVELTE

Now on the server side:

TYPESCRIPT

We set the AuthorizationToken cookie with the JWT token and return a success response.

Note here a few things:

  • The httpOnly option is set to true to prevent the cookie from being accessed by JavaScript. This is a good practice to prevent XSS attacks.

  • We set the secure option to true to ensure that the cookie is only sent over HTTPS.

  • The sameSite option set to strict for preventing the cookie from being sent in cross-site requests.

You can read the MDN documentation for more information about the Set-Cookie header.

With SvelteKit, there is no need to use third parties cookies packages, because this is handled natively by the framework.

We are also exporting a load function in this file. We're basically redirecting to the guarded page if the user is already logged in. You'll understand more how this part is handled in the hook section.

You can give a look to the loginUser() helper here.

Implementing authorization hook

If you come from a framework like Express, you might be familiar with the concept of middleware. In SvelteKit, we have something similar called hooks. These are functions that are called before a request is handled by a route.

Hooks can be defined on the server side or on the client side, or both if necessary. For this tutorial, we will define our hooks on the server side, since we are doing authentication logic.

The most used hook is the handle hook, which simply take a request and return a response.

Per convention, server hooks are defined in a /src/hooks.server.js or /src/hooks.server.ts file.

TYPESCRIPT

Here are the things that are happening in the handle hook:

  • We check if there is a AuthorizationToken cookie.

  • In case there is one, we extract the JWT token from it.

  • We verify the token using the jwt.verify function.

  • If there is any error, we simply throw it and return the response from the route.

  • If the token is valid, we get the user from the database and save it in the event.locals object.

With that in place, for every requests that come to our application, we either save or not the user ID in the locals . This gives us enough flexibility to handle authorization and necessary redirects per route.

Protecting guarded routes

For our protected routes, we will make use of SvelteKit load function. Since it runs before the component is rendered, we can use it to get the logged-in user from the locals , and either displaying the component or redirecting the user to the login page.

Our load function will be implemented in the +page.server.ts file of our guarded route.

SVELTE

When there is no user in the locals, we throw a 401 error, else we return the user to be used on the frontend.

In case there is an error, we will then have this when trying to access the guarded route:

Unauthorized error page

This is a custom error page that was generated from this error template. You can read more about custom error page here.

Wrapping up

This tutorial just shows one of the many ways to implement authentication and authorization in Svelte. There are many others aspects that I haven’t covered here. Things like implementing refreshing the token when it expires, implementing a logout or password reset endpoints. I’ve also used a very basic validation system, both on the client and on the server.

I’ll write more about these in future articles.

You might also like these blog posts

Form validation with SvelteKit and Zod

Form validation with SvelteKit and Zod

Enhance your SvelteKit forms building experience by using Zod for type safe form validation.

Understanding environment variables in SvelteKit

Understanding environment variables in SvelteKit

Environment variables are an important feature of NodeJS applications. In this article, we will learn how SvelteKit makes use of them and how to use them effectively.

Join Okupter's Mailing List

Join Okupter's mailing list to get regular updates on web development, accessibility, performance, and more.