How to add Magic Link to a SvelteKit application

Magic Staff · June 28, 2021
Download this example and get started in seconds:
npx make-magic --template svelte
How to add Magic Link to a SvelteKit application
info

🎉 Author: Sean Mullen

Shout out to Sean Mullen for being our first ever contributor to the Guest Author program!

Interested in writing for Magic? Would you mind filling out this form to join the guest author program?

note

SvelteKit is in early development at the time of writing (currently 1.0.0-next.75). Things may change, but we will try to keep this document up to date. Consult the SvelteKit documentation if running into issues.

Live Demo: https://sveltekit-magic.netlify.app.

Before we get started, it's best to understand what SvelteKit is.

From the SvelteKit documentation:

SvelteKit is a framework for building extremely high-performance web apps. ⁠ ⁠Building an app with all the modern best practices — code-splitting, offline support, server-rendered views with client-side hydration — is fiendishly complicated. SvelteKit does all the boring stuff for you so that you can get on with the creative part.

SvelteKit provides a filesystem-based router. Files in the src/routes directory represent pages and endpoints that run on the server. Pages of your application are built as Svelte components and are server-rendered when a user first visits the site. After that point any, navigation happens on the client-side.

#Getting Started

Let's start by creating a new SvelteKit project.

Bash
01npm init svelte@next sveltekit-magic

The above command will ask you some questions about how you'd like the template set up. Choose the 'SvelteKit demo app'. This comes with a Todo list application built-in. We'll make changes to the app, so the user needs to log in using Magic to access the todos.

The initialization step also asks some questions about other tools we'd like to use in our project. I like to use TypeScript, so I'll choose that here as well.

Now you can install the application dependencies and start up a development server.

Bash
01cd sveltekit-magic
02npm install
03npm run dev

Open up http://localhost:3000, and you should see something that looks like this:

#Creating the AuthForm

Now to start writing some code. First, we'll build the login page. Any Svelte components in the routes directory become pages in your SvelteKit app, so the file src/routes/login.svelte will create a page at http://localhost:3000/login. Let's create that file and add the following code.

HTML
01<!-- src/routes/login.svelte -->
02<script lang="ts">
03  let email = '';
04
05  function login() {
06    console.log(email);
07  }
08</script>
09
10<svelte:head>
11  <title>Login</title>
12</svelte:head>
13
14<div class="content">
15  <form on:submit|preventDefault="{login}">
16    <label for="email">Email</label>
17    <input id="email" bind:value="{email}" />
18    <div class="btn-container">
19      <button type="submit">Login</button>
20    </div>
21  </form>
22</div>
23
24<style>
25  .content {
26    width: 100%;
27    max-width: var(--column-width);
28    margin: var(--column-margin-top) auto 0 auto;
29  }
30
31  form {
32    width: 28rem;
33    margin: auto;
34    font-size: 1.5rem;
35  }
36
37  label {
38    display: block;
39    font-weight: bold;
40    margin-bottom: 0.25rem;
41  }
42
43  input {
44    margin-bottom: 0.75rem;
45    width: 100%;
46    padding: 0 0.5rem;
47    box-sizing: border-box;
48    height: 2.5rem;
49  }
50
51  button {
52    width: 100%;
53    background-color: var(--accent-color);
54    color: white;
55    border: none;
56    height: 2.5rem;
57    font-weight: bold;
58    transition: background-color 0.2s ease-in-out;
59    cursor: pointer;
60  }
61
62  button:hover {
63    background-color: var(--accent-hover);
64    border: 1px solid var(--accent-color);
65    color: var(--accent-color); 
66  }
67</style>

Navigate to http://localhost:3000/login, and you should see a simple form for the user to enter their email address. Right now, attempting to log in will just log the user's email to the console. We'll add more functionality to it, but first, let's create a link in the header so the user can navigate to this page easily.

Open the src/lib/header/Header.svelte file and add a link to the /login page.

HTML
01<!-- ... -->
02<ul>
03  <li class:active={$page.path === '/'}><a sveltekit:prefetch href="/">Home</a></li>
04  <li class:active={$page.path === '/about'}><a sveltekit:prefetch href="/about">About</a></li>
05  <li class:active={$page.path === '/todos'}><a sveltekit:prefetch href="/todos">Todos</a></li>
06  <!-- Add this link -->
07  <li class:active={$page.path === '/login'}><a sveltekit:prefetch href="/login">Login</a></li>
08</ul>
09<!-- ... -->

Note: To decrease load time, SvelteKit splits your code into chunks and only loads the required chunks when navigating to a page. The sveltekit:prefetch attribute loads any code and data required for a page when the user hovers over the link. This can help speed up the perceived navigation time.

It should look something like this.

#Start the Magic

Now that we have a login page that a user can navigate, we can start integrating Magic. We'll need to install the client-side and admin Magic SDKs. While we're at it, let's install a couple of other packages for encryption and environment variables.

Bash
01npm install magic-sdk @magic-sdk/admin dotenv @hapi/iron cookie

If you haven't already signed up for a Magic account, you can do so here for free.

Create a .env file at the root of the project and grab Magic publishable and secret keys. SvelteKit uses Vite as the bundler, to access the publishable key on the client-side, we need to prefix the variable with VITE_. Environment variables that do not start with VITE_ will not be written to the bundle that gets shipped to the client. The .env file should now look something like this.

Bash
01VITE_MAGIC_PUBLIC_KEY=pk_live_3*FE****222**7F4
02MAGIC_SECRET_KEY=sk_live_5*A****66**6**6
03ENCRYPTION_SECRET=some_random_string_that_is_at_least_32_characters_long

While we're at it, we should also protect our secret key by adding the .env file to our .gitignore.

Note: The dev server may need to be restarted after installing packages and editing the .env file.

#Creating the endpoints.

In SvelteKit, endpoints are JavaScript or TypeScript files that live in the routes directory and export methods that map to the HTTP methods. We will have three endpoints for handling authentication, login, logout, and user. Let's create those files now. I like to keep my endpoints in an api directory. They will be called login.ts, logout.ts, and user.ts.

We'll also create a file for instantiating the Magic admin SDK and a file for utilities. Files or folders prefixed with an underscore (_) character are hidden from the SvelteKit router. They will be called _magic.ts and _utils.ts, and they will live in the src/routes/api directory.

After you've created the files, your directory structure should look something like this:

In the _utils.ts file, we'll keep the functions for encrypting and managing the session cookies. Session cookies are pieces of data passed around in request and response headers to identify a user’s session. We’ll use the @hapi/iron package for encryption and create encrypt and decrypt convenience functions to simplify it’s usage. The cookie package is for creating the cookie headers.

Let's add those now.

Typescript
01// src/routes/api/_utils.ts
02import { serialize } from 'cookie';
03import Iron from '@hapi/iron';
04import dotenv from 'dotenv';
05
06dotenv.config();
07
08const ENCRYPTION_SECRET = process.env['ENCRYPTION_SECRET'];
09const SESSION_LENGTH_MS = 604800000;
10export const SESSION_NAME = 'session';
11
12async function encrypt(data): Promise<string> {
13  return data && Iron.seal(data, ENCRYPTION_SECRET, Iron.defaults);
14}
15
16async function decrypt<T>(data: string): Promise<T> {
17  return data && Iron.unseal(data, ENCRYPTION_SECRET, Iron.defaults);
18}
19
20export async function createSessionCookie(data: any): Promise<string> {
21  const encrypted_data = await encrypt(data);
22
23  return serialize(SESSION_NAME, encrypted_data, {
24    maxAge: SESSION_LENGTH_MS / 1000,
25    expires: new Date(Date.now() + SESSION_LENGTH_MS),
26    httpOnly: true,
27    secure: process.env['NODE_ENV'] === 'production',
28    path: '/',
29    sameSite: 'lax',
30  });
31}
32
33export async function getSession<T>(cookie: string): Promise<T> {
34  return await decrypt(cookie);
35}
36
37export function removeSessionCookie(): string {
38  return serialize(SESSION_NAME, '', {
39    maxAge: -1,
40    path: '/',
41  });
42}

#Instantiate the Magic Admin SDK

SvelteKit endpoints always run on the server, so we'll use the Magic admin SDK here. The dotenv package is used to load the environment variables to be read from process.env. Once we have the magic secret key, we can initialize the SDK and export it for the endpoints to use.

Javascript
01// src/routes/api/_magic.ts
02import { Magic } from '@magic-sdk/admin';
03import dotenv from 'dotenv';
04
05dotenv.config();
06
07const MAGIC_SECRET_KEY = process.env['MAGIC_SECRET_KEY'];
08export const magic = new Magic(MAGIC_SECRET_KEY);

#Logging into the application

In the src/routes/api/login.ts file, we'll export a post function responsible for logging the user in by validating a DID (Decentralized Identifier) token that will be generated on the client side and then returning a cookie to the client to track the session.

Let's see the whole endpoint, and then we’ll break down the most important parts.

Typescript
01// src/routes/api/login.ts
02import type { Request, Response } from '@sveltejs/kit';
03import { magic } from './_magic';
04import { createSessionCookie } from './_utils';
05
06export async function post(req: Request): Promise<Response> {
07  try {
08    // Parse and validate the DID token
09    const didToken = magic.utils.parseAuthorizationHeader(req.headers['authorization']);
10    magic.token.validate(didToken);
11
12    // Token is valid, so get the user metadata and set it in a cookie.
13    const metadata = await magic.users.getMetadataByToken(didToken);
14    const cookie = await createSessionCookie(metadata);
15
16    return {
17      status: 200,
18      headers: {
19        'set-cookie': cookie,
20      },
21      body: {
22        user: metadata,
23      },
24    };
25  } catch (err) {
26    return {
27      status: 500,
28      body: {
29        error: {
30          message: 'Internal Server Error',
31        },
32      },
33    };
34  }
35}

First, we'll use the Magic SDK to read and validate the token.

Typescript
01const didToken = magic.utils.parseAuthorizationHeader(req.headers['authorization']);
02magic.token.validate(didToken);

The DID token will be sent as an authorization header, which is parsed using the magic.utils.parseAuthorizationHeader function. It is then validated using magic.token.validate.

If the token is not valid, it will throw an error. If the token is valid, we can use it to get information about the user. We'll put that information in the session cookie, so when the user makes subsequent requests, we'll know who they're.

Typescript
01const metadata = await magic.users.getMetadataByToken(didToken);
02const cookie = await createSessionCookie(metadata); 
03// NOTE: createSessionCookie is implemented in _utils.ts

When the user successfully logs in, we return the metadata and set the cookie with the set-cookie header. In this example, we're sending a status 500 error code if anything goes wrong. In a real-world application, you may want to be more specific about the issue so the client can handle the type of error appropriately.

#Client-side login

Now that we have the login endpoint let's call it from the client. Create a file called auth.ts in src/lib. Here we'll put the functions that will call the authentication endpoints, and we'll also create a Svelte store for keeping information about the logged-in user. First, let's import the dependencies. We'll need the client-side Magic SDK and a writable store.

The store will either contain user information or be null. Based on the store’s state, we can change the display to reflect that a user is logged in or logged out.

Typescript
01// src/lib/auth.ts
02import { Magic } from 'magic-sdk';
03import { writable } from 'svelte/store';
04import { goto } from '$app/navigation';
05
06export const store = writable(null);

The Magic SDK also needs to be instantiated here, but it’s slightly more complex due to the nature of SvelteKit. The Magic SDK can only be used in browser environments, but pages in SvelteKit can be rendered either server-side or client-side, so we need to make sure that Magic is only run on the client. To do that, we'll create a createMagic function that will only be called when the user does actions, such as attempting to log in or log out. The first time createMagic is called, it will instantiate the client-side SDK. If it is called again, it will return the previously created instance.

Javascript
01// src/lib/auth.ts
02let magic;
03
04function createMagic() {
05  magic = magic || new Magic(import.meta.env.VITE_MAGIC_PUBLIC_KEY as string);
06  return magic;
07}

Now let's create the login function. Instead of just logging the user's email to the console, we'll pass it to this function which will call the magic.auth.loginWithMagicLink method to log the user in and generate a DID token. We'll send that token using a fetch request to the login endpoint we just created. If everything goes to plan, the fetch should return the user metadata, which we will set in the store.

Typescript
01// src/lib/auth.ts
02export async function login(email: string): Promise<void> {
03  const magic = createMagic();
04
05  const didToken = await magic.auth.loginWithMagicLink({ email });
06
07  // Validate the did token on the server
08  const res = await fetch('/api/login', {
09    method: 'POST',
10    headers: {
11      'Content-Type': 'application/json',
12      Authorization: `Bearer ${didToken}`,
13    },
14  });
15
16  if (res.ok) {
17    const data = await res.json();
18    store.set(data.user);
19  }
20}

Now in the login.svelte page component, import the auth function and call it with the user's email when they submit the form. If the login is successful, we'll navigate to the 'todos' page. Update the <script> tag in the src/routes/login.svelte to look as follows.

HTML
01<!-- src/routes/login.svelte -->
02<script lang="ts">
03  import * as auth from '$lib/auth';
04  import { goto } from '$app/navigation';
05
06  let email = '';
07
08  async function login() {
09    try {
10      await auth.login(email);
11      goto('/todos');
12    } catch (err) {
13      console.log(err);
14    }
15  }
16</script>

#Protecting the todos

At this point, you should be able to log into the application successfully. But there's a problem. Users that haven't logged in can also access the 'todos' page. It's time to fix that.

To do that, we'll use SvelteKit's load function to call the user endpoint. The load function runs before the component is rendered and can run on either the client- or server-side, so SvelteKit passes it a fetch function that is agnostic of the environment. In the src/routes/__layout.svelte component, add the following code. It will call the endpoint to see if the user is logged in and set their metadata in the store.

HTML
01<!-- src/routes/__layout.svelte -->
02<script lang="ts" context="module">
03  import { store as authStore } from '$lib/auth';
04
05  export async function load({ fetch }) {
06    const res = await fetch('/api/user');
07    const { user } = await res.json();
08    authStore.set(user);
09    return {
10      status: 200,
11    };
12  }
13</script>

Note that this is a context="module" script tag. This only runs when the module first evaluates and before any rendering happens.

Every request in SvelteKit runs through the handle function defined in src/hooks.ts. It is here that we'll check to see if the user has a session cookie. If they do, we'll get the user metadata from the cookie and set it on the request to be available to the endpoints. Update the src/hooks.ts file, so it is as follows.

Typescript
01// src/hooks.ts
02import cookie from 'cookie';
03import type { Handle } from '@sveltejs/kit';
04import { getSession, SESSION_NAME } from './routes/api/_utils';
05
06export const handle: Handle = async ({ request, resolve }) => {
07  const cookies = cookie.parse(request.headers.cookie || '');
08
09  const user = await getSession(cookies[SESSION_NAME]);
10  request.locals.user = user;
11  request.locals.userid = user?.publicAddress;
12
13  // TODO https://github.com/sveltejs/kit/issues/1046
14  if (request.query.has('_method')) {
15    request.method = request.query.get('_method').toUpperCase();
16  }
17
18  const response = await resolve(request);
19
20  return response;
21};

Now in the user endpoint, we'll export a get function. If there is no user on the req.locals object, the user is not logged in, so we send back null. Otherwise, we'll refresh the cookie to extend their session and return the user metadata in the body.

Typescript
01// src/routes/api/user.ts
02import type { Request, Response } from '@sveltejs/kit';
03import { createSessionCookie } from './_utils';
04
05export async function get(req: Request): Promise<Response> {
06  try {
07    if (!req.locals.user) {
08      return {
09        status: 200,
10        body: {
11          user: null,
12        },
13      };
14    }
15
16    const user = req.locals.user;
17
18    // Refresh session
19    const cookie = await createSessionCookie(user);
20
21    return {
22      status: 200,
23      headers: {
24        'set-cookie': cookie,
25      },
26      body: {
27        user,
28      },
29    };
30  } catch (err) {
31    return {
32      status: 500,
33      body: {
34        error: {
35          message: 'Internal Server Error',
36        },
37      },
38    };
39  }
40}

Now let's create a src/routes/todos/__layout.svelte component. We'll again use the load function, this time to check that a user is in the authentication store. Because this layout is nested in a deeper path than the src/routes/__layout.ts file, we know that this will run after the call to the /api/user endpoint. If there is no user in the store, we'll redirect the user to the login page. Otherwise, we can show them their todos. Here is the entirety of the src/routes/todos/__layout.svelte file.

HTML
01<!-- src/routes/todos/__layout.svelte -->
02<script lang="ts" context="module">
03  import { get } from 'svelte/store';
04  import { store as authStore } from '$lib/auth';
05
06  export function load() {
07    const user = get(authStore);
08    if (!user) {
09      return {
10        status: 302,
11        redirect: '/auth',
12      };
13    }
14    return {
15      status: 200,
16    };
17  }
18</script>
19
20<slot />

#Logging out

Finally, we need to allow the user to log out. Let's start by changing the Header component, so it displays 'LOGOUT' rather than 'LOGIN' for the logged-in client. In src/lib/header/Header.svelte import the authentication store and subscribe to it.

HTML
01<!-- src/lib/header/Header.svelte -->
02<script lang="ts">
03  // ...
04  import { store as authStore, logout } from '$lib/auth';
05
06  $: user = $authStore;
07</script>

We'll use an #if block to change the display based on the user. If there is no user in the store, we'll display the LOGIN link we previously created. Otherwise, we'll call a function to log the user out.

HTML
01{#if user}
02  <li class:active={$page.path === '/auth'}>
03    <a href="javascript:void(0)" on:click|preventDefault={logout}>Logout</a>
04  </li>
05{:else}
06  <li class:active={$page.path === '/auth'}><a href="/auth">Login</a></li>
07{/if}

The logout function will live in the src/lib/auth.ts file. It will call the /api/logout endpoint and clear the current user from the store. After that's complete, you can redirect the user to wherever makes sense. Here we'll send them back to the login page.

Typescript
01// src/lib/auth.ts
02export async function logout(): Promise<void> {
03  await fetch('/api/logout');
04  store.set(null);
05  goto('/auth');
06}

The last piece of the puzzle is to implement the logout endpoint. We can use the magic.users.logoutByIssuer method to log out the user with Magic. First, import our Magic SDK instance. Remember that user is set on request.locals in the handle hook. The issuer property is part of the user metadata, and we'll pass that to the logoutByIssuer method. This method needs to be wrapped in a try/catch block because it will throw an error if the user has already logged out or their magic session expired.

Whenever a user requests our application, we're not reaching out to Magic to see if they are logged in. We’re relying on our session cookie, so we need to clear that cookie as well. Import the removeSessionCookie method from the utils.ts file. That will create a cookie that clears the previous cookie and send the cookie along in the headers.

Typescript
01// src/routes/api/logout.ts
02import type { Request, Response } from '@sveltejs/kit';
03import { magic } from './_magic';
04import { removeSessionCookie } from './_utils';
05
06export async function get(req: Request): Promise<Response> {
07  const cookie = removeSessionCookie();
08
09  try {
10    await magic.users.logoutByIssuer(req.locals.user.issuer);
11  } catch (err) {
12    console.log('Magic session already expired');
13  }
14
15  return {
16    status: 200,
17    headers: {
18      'set-cookie': cookie,
19    },
20    body: {},
21  };
22}

And that's it! We now have Magic auth fully integrated into the SvelteKit todos app.

Check out the full example on Github: https://github.com/srmullen/sveltekit-magic or see it in action here: https://sveltekit-magic.netlify.app.

Let's make some magic!