Handling authentication and authorization with JWT in SvelteKit
Justin Ahinon
Last updated on
Heads up!
Svelte version: 3.58.0
SvelteKit version: 1.15.5
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 application 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 and reading various repositories codes 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 handle server-side code?
In SvelteKit, you have two main ways to run server-side code: API routes (or endpoints, as they are 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 as a 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 form submission.
This tutorial’ll create a small project with a sign-up, login, and guarded pages. Our authentication and authorization login is 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 an 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:
code loading...
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:
code loading...
Now we will install bcryptjs
to hash and compare passwords, jwt
to generate and verify tokens, and @prisma/client to interact with our database:
code loading...
When using TypeScript, some dependencies require type definitions. We install them with the following command:
code loading...
Setting up the database
Let’s now use Prisma to initialize an SQLite database and create a User model.
code loading...
In our schema.prisma
file, we will create a simple User model with email and password fields.
code loading...
We can generate the Prisma client and apply our schema changes to the database by running
code loading...
How does JWT work?
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 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:
Authentication pages for our app
Now that we understand 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, password input, and a submit button.
code loading...
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:
code loading...
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, creating a new user, returning 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 makes the experience smoother with progressive enhancement. We do that by adding the use:enhance
action to our form element.
With that added, the form will be submitted with client-side JavaScript, making it a better user experience.
code loading...
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:
code loading...
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:
Login
The process for logging in is a bit similar to 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:
code loading...
Now on the server side:
code loading...
We set the AuthorizationToken
cookie with the JWT token and return a successful response.
Note here a few things:
The
httpOnly
option is set totrue
to prevent the cookie from being accessed by JavaScript. This is a good practice to prevent XSS attacks.We set the
secure
option totrue
to ensure that the cookie is only sent over HTTPS.The
sameSite
option is set tostrict
to prevent 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-party cookies packages because the framework handles this natively.
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 about how this part is handled in the hook section.
You can give a look at 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 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. We will define our hooks on the server side for this tutorial, since we are doing authentication logic.
The most used hook is the handle
hook, which simply takes a request and returns a response.
Per convention, server hooks are defined in a /src/hooks.server.js
or /src/hooks.server.ts
file.
code loading...
Here are the things that are happening in the handle
hook:
We check if there is an
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 request that comes 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 display the component or redirect the user to the login page.
Our load
function will be implemented in our guarded route's +page.server.ts
file.
code loading...
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:
This is a custom error page that was generated from this error template. You can read more about custom error pages in Svelte here.
Wrapping up
This tutorial just shows one of the many ways to implement authentication and authorization in Svelte. There are many other 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.
Get help with your Svelte or SvelteKit code
Got a Svelte/Sveltekit bug giving you headaches? I’ve been there!
Book a free 15 min consultation call, and I’ll review your code base and give you personalized feedback on your code.
P.S. If you have a bigger problem that may need more than 15 minutes, you can also pick my brain for a small fee. 😊 But that’s up to you!