Frontend Masters Boost RSS Feed https://frontendmasters.com/blog Helping Your Journey to Senior Developer Fri, 19 Jul 2024 18:40:24 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 225069128 Introducing Svelte 5 https://frontendmasters.com/blog/introducing-svelte-5/ https://frontendmasters.com/blog/introducing-svelte-5/#comments Fri, 19 Jul 2024 18:40:23 +0000 https://frontendmasters.com/blog/?p=3067 Svelte has always been a delightful, simple, and fun framework to use. It’s a framework that’s always prioritized developer experience (DX), while producing a light and fast result with minimal JavaScript. It achieves this nice DX by giving users dirt simple idioms and a required compiler that makes everything work. Unfortunately, it used to be fairly easy to break Svelte’s reactivity. It doesn’t matter how fast a website is if it’s broken.

These reliability problems with reactivity are gone in Svelte 5.

In this post, we’ll get into the exciting Svelte 5 release (in Beta at the time of this writing). Svelte is the latest framework to add signals to power their reactivity. Svelte is now every bit as capable of handling robust web applications, with complex state, as alternatives like React and Solid. Best of all, it achieved this with only minimal hits to DX. It’s every bit as fun and easy to use as it was, but it’s now truly reliable, while still producing faster and lighter sites.

Let’s jump in!

The Plan

Let’s go through various pieces of Svelte, look at the “old” way, and then see how Svelte 5 changes things for the better. We’ll cover:

  1. State
  2. Props
  3. Effects

If you find this helpful, let me know, as I’d love to cover snippets and Svelte’s exciting new fine-grained reactivity.

As of this writing, Svelte 5 is late in the Beta phase. The API should be stable, although it’s certainly possible some new things might get added.

The docs are also still in beta, so here’s a preview URL for them. Svelte 5 might be released when you read this, at which point these docs will be on the main Svelte page. If you’d like to see the code samples below in action, you can find them in this repo.

State

Effectively managing state is probably the most crucial task for any web framework, so let’s start there.

State used to be declared with regular, plain old variable declarations, using let.

let value = 0;

Derived state was declared with a quirky, but technically valid JavaScript syntax of $:. For example:

let value = 0;
$: doubleValue = value * 2;

Svelte’s compiler would (in theory) track changes to value, and update doubleValue accordingly. I say in theory since, depending on how creatively you used value, some of the re-assignments might not make it to all of the derived state that used it.

You could also put entire code blocks after $: and run arbitrary code. Svelte would look at what you were referencing inside the code block, and re-run it when those things changed.

$: {
  console.log("Value is ", value);
}

Stores

Those variable declarations, and the special $: syntax was limited to Svelte components. If you wanted to build some portable state you could define anywhere, and pass around, you’d use a store.

We won’t go through the whole API, but here’s a minimal example of a store in action. We’ll define a piece of state that holds a number, and, based on what that number is at anytime, spit out a label indicating whether the number is even or odd. It’s silly, but it should show us how stores work.

import { derived, writable } from "svelte/store";

export function createNumberInfo(initialValue: number = 0) {
  const value = writable(initialValue);

  const derivedInfo = derived(value, value => {
    return {
      value,
      label: value % 2 ? "Odd number" : "Even number",
    };
  });

  return {
    update(newValue: number) {
      value.set(newValue);
    },
    numberInfo: derivedInfo,
  };
}

Writable stores exist to write values to. Derived stores take one or more other stores, read their current values, and project a new payload. If you want to provide a mechanism to set a new value, close over what you need to. To consume a store’s value, prefix it with a $ in a Svelte component. It’s not shown here, but there’s also a subscribe method on stores, and a get import. If the store returns an object with properties, you can either “dot through” to them, or you can use a reactive assignment ($:) to get those nested values. The example below shows both, and this distinction will come up later when we talk about interoperability between Svelte 4 and 5.

<script lang="ts">
  import { createNumberInfo } from './numberInfoStore';

  let store = createNumberInfo(0);

  $: ({ numberInfo, update } = store);
  $: ({ label, value } = $numberInfo);
</script>

<div class="flex flex-col gap-2 p-5">
  <span>{$numberInfo.value}</span>
  <span>{$numberInfo.label}</span>
  <hr />
  <span>{value}</span>
  <span>{label}</span>

  <button onclick={() => update($numberInfo.value + 1)}>
    Increment count
  </button>
</div>

This was the old Svelte.

This is a post on the new Svelte, so let’s turn our attention there.

State in Svelte 5

Things are substantially simpler in Svelte 5. Pretty much everything is managed by something new called “runes.” Let’s see what that means.

Runes

Svelte 5 joins the increasing number of JavaScript frameworks that use the concept of signals. There is a new feature called runes and under the covers they use signals. These accomplish a wide range of features from state to props and even side effects. Here’s a good introduction to runes.

To create a piece of state, we use the $state rune. You don’t import it, you just use it — it’s part of the Svelte language.

let count = $state(0);

For values with non-inferable types, you can provide a generic

let currentUser = $state<User | null>(null);

What if you want to create some derived state? Before we did:

$: countTimes2 = count * 2;

In Svelte 5 we use the $derived rune.

let countTimes2 = $derived(count * 2);

Note that we pass in a raw expression. Svelte will run it, see what it depends on, and re-run it as needed. There’s also a $derived.by rune if you want to pass an actual function.

If you want to use these state values in a Svelte template, you just use them. No need for special $ syntax to prefix the runes like we did with stores. You reference the values in your templates, and they update as needed.

If you want to update a state value, you assign to it:

count = count + 1;
// or count++;

What about stores?

We saw before that defining portable state outside of components was accomplished via stores. Stores are not deprecated in Svelte 5, but there’s a good chance they’re on their way out of the framework. You no longer need them, and they’re replaced with what we’ve already seen. That’s right, the $state and $derived runes we saw before can be defined outside of components in top-level TypeScript (or JavaScript) files. Just be sure to name your file with a .svelte.ts extension, so the Svelte compiler knows to enable runes in these files. Let’s take a look!

Let’s re-implement our number / label code from before, in Svelte 5. This is what it looked like with stores:

import { derived, writable } from "svelte/store";

export function createNumberInfo(initialValue: number = 0) {
  const value = writable(initialValue);

  const derivedInfo = derived(value, value => {
    return {
      value,
      label: value % 2 ? "Odd number" : "Even number",
    };
  });

  return {
    update(newValue: number) {
      value.set(newValue);
    },
    numberInfo: derivedInfo,
  };
}

Here it is with runes:

export function createNumberInfo(initialValue: number = 0) {
  let value = $state(initialValue);
  let label = $derived(value % 2 ? "Odd number" : "Even number");

  return {
    update(newValue: number) {
      value = newValue;
    },
    get value() {
      return value;
    },
    get label() {
      return label;
    },
  };
}

It’s 3 lines shorter, but more importantly, much simpler. We declared our state. We computed our derived state. And we send them both back, along with a method that updates our state.

You may be wondering why we did this:

  get value() {
    return value;
  },
  get label() {
    return label;
  }

rather than just referencing those properties. The reason is that reading that state, at any given point in time, evaluates the state rune, and, if we’re reading it in a reactive context (like a Svelte component binding, or inside of a $derived expression), then a subscription is set up to update any time that piece of state is updated. If we had done it like this:

// this won't work
return {
  update(newValue: number) {
    value = newValue;
  },
  value,
  label,
};

That wouldn’t have worked because those value and label pieces of state would be read and evaluated right there in the return value, with those raw values getting injected into that object. They would not be reactive, and they would never update.

That’s about it! Svelte 5 ships a few universal state primitives which can be used outside of components and easily constructed into larger reactive structures. What’s especially exciting is that Svelte’s component bindings are also updated, and now support fine-grained reactivity that didn’t used to exist.

Props

Defining state inside of a component isn’t too useful if you can’t pass it on to other components as props. Props are also reworked in Svelte 5 in a way that makes them simpler, and also, as we’ll see, includes a nice trick to make TypeScript integration more powerful.

Svelte 4 props were another example of hijacking existing JavaScript syntax to do something unrelated. To declare a prop on a component, you’d use the export keyword. It was weird, but it worked.

// ChildComponent.svelte
<script lang="ts">
  export let name: string;
  export let age: number;
  export let currentValue: string;
</script>

<div class="flex flex-col gap-2">
  {name} {age}
  <input bind:value={currentValue} />
</div>

This component created three props. It also bound the currentValue prop into the <input>, so it would change as the user typed. Then to render this component, we’d do something like this:

<script lang="ts">
  import ChildComponent from "./ChildComponent.svelte";

  let currentValue = "";
</script>

Current value in parent: {currentValue}
<ChildComponent name="Bob" age={20} bind:currentValue />

This is Svelte 4, so let currentValue = '' is a piece of state that can change. We pass props for name and age, but we also have bind:currentValue which is a shorthand for bind:currentValue={currentValue}. This creates a two-way binding. As the child changes the value of this prop, it propagates the change upward, to the parent. This is a very cool feature of Svelte, but it’s also easy to misuse, so exercise caution.

If we type in the ChildComponent’s <input>, we’ll see currentValue update in the parent component.

Svelte 5 version

Let’s see what these props look like in Svelte 5.

<script lang="ts">
  type Props = {
    name: string;
    age: number;
    currentValue: string;
  };

  let { age, name, currentValue = $bindable() }: Props = $props();
</script>

<div class="flex flex-col gap-2">
  {name} {age}
  <input bind:value={currentValue} />
</div>

The props are defined via the $props rune, from which we destructure the individual values.

let { age, name, currentValue = $bindable() }: Props = $props();

We can apply typings directly to the destructuring expression. In order to indicate that a prop can be (but doesn’t have to be) bound to the parent, like we saw above, we use the $bindable rune, like this

 = $bindable()

If you want to provide a default value, assign it to the destructured value. To assign a default value to a bindable prop, pass that value to the $bindable rune.

let { age = 10, name = "foo", currentValue = $bindable("bar") }: Props = $props();

But wait, there’s more!

One of the most exciting changes to Svelte’s prop handling is the improved TypeScript integration. We saw that you can assign types, above. But what if we want to do something like this (in React)

type Props<T> = {
  items: T[];
  onSelect: (item: T) => void;
};
export const AutoComplete = <T,>(props: Props<T>) => {
  return null;
};

We want a React component that receives an array of items, as well as a callback that takes a single item (of the same type). This works in React. How would we do it in Svelte?

At first, it looks easy.

<script lang="ts">
  type Props<T> = {
    items: T[];
    onSelect: (item: T) => void;
  };

  let { items, onSelect }: Props<T> = $props();
  //         Error here _________^
</script>

The first T is a generic parameter, which is defined as part of the Props type. This is fine. The problem is, we need to instantiate that generic type with an actual value for T when we attempt to use it in the destructuring. The T that I used there is undefined. It doesn’t exist. TypeScript has no idea what that T is because it hasn’t been defined.

What changed?

Why did this work so easily with React? The reason is, React components are functions. You can define a generic function, and when you call it TypeScript will infer (if it can) the values of its generic types. It does this by looking at the arguments you pass to the function. With React, rendering a component is conceptually the same as calling it, so TypeScript is able to look at the various props you pass, and infer the generic types as needed.

Svelte components are not functions. They’re a proprietary bit of code thrown into a .svelte file that the Svelte compiler turns into something useful. We do still render Svelte components, and TypeScript could easily look at the props we pass, and infer back the generic types as needed. The root of the problem, though, is that we haven’t (yet) declared any generic types that are associated with the component itself. With React components, these are the same generic types we declare for any function. What do we do for Svelte?

Fortunately, the Svelte maintainers thought of this. You can declare generic types for the component itself with the generics attribute on the <script> tag at the top of your Svelte component:

<script lang="ts" generics="T">
  type Props<T> = {
    items: T[];
    onSelect: (item: T) => void;
  };

  let { items, onSelect }: Props<T> = $props();
</script>

You can even define constraints on your generic arg:

<script lang="ts" generics="T extends { name: string }">
  type Props<T> = {
    items: T[];
    onSelect: (item: T) => void;
  };

  let { items, onSelect }: Props<T> = $props();
</script>

TypeScript will enforce this. If you violate that constraint like this:

<script lang="ts">
  import AutoComplete from "./AutoComplete.svelte";

  let items = [{ name: "Adam" }, { name: "Rich" }];
  let onSelect = (item: { id: number }) => {
    console.log(item.id);
  };
</script>

<div>
  <AutoComplete {items} {onSelect} />
</div>

TypeScript will let you know:

Type '(item: { id: number; }) => void' is not assignable to type '(item: { name: string; }) => void'. Types of parameters 'item' and 'item' are incompatible.

Property 'id' is missing in type '{ name: string; }' but required in type '{ id: number; }'.

Effects

Let’s wrap up with something comparatively easy: side effects. As we saw before, briefly, in Svelte 4 you could run code for side effects inside of $: reactive blocks

$: {
  console.log(someStateValue1, someStateValue2);
}

That code would re-run when either of those values changed.

Svelte 5 introduces the $effect rune. This will run after state has changed, and been applied to the dom. It is for side effects. Things like resetting the scroll position after state changes. It is not for synchronizing state. If you’re using the $effect rune to synchronize state, you’re probably doing something wrong (the same goes for the useEffect hook in React).

The code is pretty anti-climactic.

$effect(() => {
  console.log("Current count is ", count);
});

When this code first starts, and anytime count changes, you’ll see this log. To make it more interesting, let’s pretend we have a current timestamp value that auto-updates:

let timestamp = $state(+new Date());
setInterval(() => {
  timestamp = +new Date();
}, 1000);

We want to include that value when we log, but we don’t want our effect to run whenever our timestamp changes; we only want it to run when count changes. Svelte provides an untrack utility for that

import { untrack } from "svelte";

$effect(() => {
  let timestampValue = untrack(() => timestamp);
  console.log("Current count is ", count, "at", timestampValue);
});

Interop

Massive upgrades where an entire app is updated to use a new framework version’s APIs are seldom feasible, so it should come as no surprise that Svelte 5 continues to support Svelte 4. You can upgrade your app incrementally. Svelte 5 components can render Svelte 4 components, and Svelte 4 components can render Svelte 5 components. The one thing you can’t do is mix and match within a single component. You cannot use reactive assignments $: in the same component that’s using Runes (the Svelte compiler will remind you if you forget).

Since stores are not yet deprecated, they can continue to be used in Svelte 5 components. Remember the createNumberInfo method from before, which returned an object with a store on it? We can use it in Svelte 5. This component is perfectly valid, and works.

<script lang="ts">
  import { createNumberInfo } from '../svelte4/numberInfoStore';

  const numberPacket = createNumberInfo(0);

  const store = numberPacket.numberInfo;
  let junk = $state('Hello');
</script>

<span>Run value: {junk}</span>
<div>Number value: {$store.value}</div>

<button onclick={() => numberPacket.update($store.value + 1)}>Update</button>

But the rule against reactive assignments still holds; we cannot use one to destructure values off of stores when we’re in Svelte 5 components. We have to “dot through” to nested properties with things like {$store.value} in the binding (which always works) rather than:

$: ({ value } = $store);

… which generates the error of:

$: is not allowed in runes mode, use $derived or $effect instead

The error is even clear enough to give you another alternative to inlining those nested properties, which is to create a $derived state:

let value = $derived($store.value);
// or let { value } = $derived($store);

Personally I’m not a huge fan of mixing the new $derived primitive with the old Svelte 4 syntax of $store, but that’s a matter of taste.

Parting thoughts

Svelte 5 has shipped some incredibly exciting changes. We covered the new, more reliable reactivity primitives, the improved prop management with tighter TypeScript integration, and the new side effect primitive. But we haven’t come closing to covering everything. Not only are there more variations on the $state rune, but Svelte 5 also updated it’s event handling mechanism, and even shipped an exciting new way to re-use “snippets” of HTML.

Svelte 5 is worth a serious look for your next project.

]]>
https://frontendmasters.com/blog/introducing-svelte-5/feed/ 1 3067
Using Auth.js with SvelteKit https://frontendmasters.com/blog/using-nextauth-now-auth-js-with-sveltekit/ https://frontendmasters.com/blog/using-nextauth-now-auth-js-with-sveltekit/#respond Mon, 29 Apr 2024 15:22:25 +0000 https://frontendmasters.com/blog/?p=1764 SvelteKit is an exciting framework for shipping performant web applications with Svelte. I’ve previously written an introduction on it, as well as a deeper dive on data handling and caching.

In this post, we’ll see how to integrate Auth.js (Previously next-auth) into a SvelteKit app. It might seem surprising to hear that this works with SvelteKit, but this project has gotten popular enough that much of it has been split into a framework-agnostic package of @auth/core. The Auth.js name is actually a somewhat recent rebranding of NextAuth.

In this post we’ll cover the basic config for @auth/core: we’ll add a Google Provider and configure our sessions to persist in DynamoDB.

The code for everything is here in a GitHub repo, but you won’t be able to run it without setting up your own Google Application credentials, as well as a Dynamo table (which we’ll get into).

The initial setup

We’ll build the absolute minimum skeleton app needed to demonstrate authentication. We’ll have our root layout read whether the user is logged in, and show a link to content that’s limited to logged in users, and a log out button if so; or a log in button if not. We’ll also set up an auth check with redirect in the logged in content, in case the user browses directly to the logged in URL while logged out.

Let’s create a SvelteKit project if we don’t have one already, using the insutructions here. Chose “Skeleton Project” when prompted.

Now let’s install some packages we’ll be using:

npm i @auth/core @auth/sveltekit

Let’s create a top-level layout that will use our auth data. First, our server loader, in a file named +layout.server.ts. This will hold our logged-in state, which for now is always false.

export const load = async ({ locals }) => {
  return {
    loggedIn: false,
  };
};

Now let’s make the actual layout, in +layout.svelte with some basic markup

<script lang="ts">
  import type { PageData } from './$types';
  import { signIn, signOut } from '@auth/sveltekit/client';

  export let data: PageData;
  $: loggedIn = data.loggedIn;
</script>

<main>
  <h1>Hello there! This is the shared layout.</h1>

  {#if loggedIn}
    <div>Welcome!</div>
    <a href="/logged-in">Go to logged in area</a>
    <br />
    <br />
    <button on:click={() => signOut()}>Log Out</button>
  {:else}
    <button on:click={() => signIn('google')}>Log in</button>
  {/if}
  <section>
    <slot />
  </section>
</main>

There should be a root +page.svelte file that was generated when you scaffolded the project, with something like this in there

<h1>This is the home page</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the SvelteKit docs</p>

Feel free to just leave it.

Next, we’ll create a route called logged-in. Create a folder in routes called logged-in and create a +page.server.ts which for now will always just redirect you out.

import { redirect } from "@sveltejs/kit";

export const load = async ({}) => {
  redirect(302, "/");
};

Now let’s create the page itself, in +page.svelte and add some markup

<h3>This is the logged in page</h3>

And that’s about it. Check out the GitHub repo to see everything, including just a handful of additional styles.

Adding Auth

Let’s get started with the actual authentication.

First, create an environment variable in your .env file called AUTH_SECRET and set it to a random string that’s at least 32 characters. If you’re looking to deploy this to a host like Vercel or Netlify, be sure to add your environment variable in your project’s settings according to how that host does things.

Next, create a hooks.server.ts (or .js) file directly under src. The docs for this file are here, but it essentially allows you to add application-wide wide side effects. Authentication falls under this, which is why we configure it here.

Now let’s start integrating auth. We’ll start with a very basic config:

import { SvelteKitAuth } from "@auth/sveltekit";
import { AUTH_SECRET } from "$env/static/private";

const auth = SvelteKitAuth({
  providers: [],
  session: {
    maxAge: 60 * 60 * 24 * 365,
    strategy: "jwt",
  },

  secret: AUTH_SECRET,
});

export const handle = auth.handle;

We tell auth to store our authentication info in a JWT token, and configure a max age for the session as 1 year. We provide our secret, and a (currently empty) array of providers.

Adding our provider

Providers are what perform the actual authentication of a user. There’s a very, very long list of options to choose from, which are listed here. We’ll use Google. First, we’ll need to create application credentials. So head on over to the Google Developers console. Click on credentials, and then “Create Credentials”

Click it, then choose “OAuth Client ID.” Choose web application, and give your app a name.

For now, leave the other options empty, and click Create.

Screenshot

Before closing that modal, grab the client id, and client secret values, and paste them into environment variables for your app

GOOGLE_AUTH_CLIENT_ID=....
GOOGLE_AUTH_SECRET=....

Now let’s go back into our hooks.server.ts file, and import our new environment variables:

import { AUTH_SECRET, GOOGLE_AUTH_CLIENT_ID, GOOGLE_AUTH_SECRET } from "$env/static/private";

and then add our provider

providers: [
  GoogleProvider({
    clientId: GOOGLE_AUTH_CLIENT_ID,
    clientSecret: GOOGLE_AUTH_SECRET
  })
],

and then export our auth handler as our hooks handler.

export const handle = auth.handle;

Note that if you had other handlers you wanted SvelteKit to run, you can use the sequence helper:

import { sequence } from "@sveltejs/kit/hooks";

export const handle = sequence(otherHandleFn, auth.handle);

Unfortunately if we try to login now, we’re greeted by an error:

Clicking error details provides some more info:

We need to tell Google that this redirect URL is in fact valid. Go back to our Google Developer Console, open the credentials we just created, and add this URL in the redirect urls section.

And now, after saving (and possibly waiting a few seconds) we can click login, and see a list of our Google accounts available, and pick the one we want to log in with

Choosing one of the accounts should log you in, and bring you right back to the same page you were just looking at.

So you’ve successfully logged in, now what?

Being logged in is by itself useless without some way to check logged in state, in order to change content and grant access accordingly. Let’s go back to our layout’s server loader

export const load = async ({ locals }) => {
  return {
    loggedIn: false,
  };
};

We previously pulled in that locals property. Auth.js adds a getSession method to this, which allows us to grab the current authentication, if any. We just logged in, so let’s grab the session and see what’s there

export const load = async ({ locals }) => {
  const session = await locals.getSession();
  console.log({ session });

  return {
    loggedIn: false,
  };
};

For me, this logs the following:

All we need right now is a simple boolean indicating whether the user is logged in, so let’s send down a boolean on whether the user object exists:

export const load = async ({ locals }) => {
  const session = await locals.getSession();
  const loggedIn = !!session?.user;

  return {
    loggedIn,
  };
};

and just like that, our page updates:

The link to our logged-in page still doesn’t work, since it’s still always redirecting. We could run the same code we did before, and call locals.getSession to see if the user is logged in. But we already did that, and stored the loggedIn property in our layout’s loader. This makes it available to any routes underneath. So let’s grab it, and conditionally redirect based on its value.

import { redirect } from "@sveltejs/kit";

export const load = async ({ parent }) => {
  const parentData = await parent();

  if (!parentData.loggedIn) {
    redirect(302, "/");
  }
};

And now our logged-in page works:

Persisting our authentication

We could end this post here. Our authentication works, and we integrated it into application state. Sure, there’s a myriad of other auth providers (GitHub, Facebook, etc), but those are just variations on the same theme.

But one topic we haven’t discussed is authentication persistence. Right now our entire session is stored in a JWT, on our user’s machine. This is convenient, but it does offer some downsides, namely that this data could be stolen. An alternative is to persist our users’ sessions in an external database. This post discusses the various tradeoffs, but most of the downsides of stateful (i.e. stored in a database) solutions are complexity and the burden of having to reach out to an external storage to grab session info. Fortunately, Auth.js removes the complexity burden for us. As far as performance concerns, we can choose a storage mechanism that’s known for being fast and effective: in our case we’ll look at DynamoDB.

Adapters

The mechanism by which Auth.js persists our authentication sessions is database adapters. As before, there are many to choose from. We’ll use DynamoDB. Compared to providers, the setup for database adapters is a bit more involved, and a bit more tedious. In order to keep the focus of this post on Auth.js, we won’t walk through setting up each and every key field, TTL setting, and GSI—to say nothing of AWS credentials if you don’t have them already. If you’ve never used Dynamo and are curious, I wrote an introduction here. If you’re not really interested in Dynamo, this section will show you the basics of setting up database adapters, which you can apply to any of the (many) others you might prefer to use.

That said, if you’re interested in implementing this yourself, the adapter docs provide CDK and CloudFormation templates for the Dynamo table you need, or if you want a low-dev-ops solution, it even lists out the keys, TTL and GSI structure here, which is pretty painless to just set up.

We’ll assume you’ve got your DynamoDB instance set up, and look at the code to connect it. First, we’ll install some new libraries

npm i @auth/dynamodb-adapter @aws-sdk/lib-dynamodb @aws-sdk/client-dynamodb

First, make sure your dynamo table name, as well as your AWS credentials are in environment variables

Now we’ll go back to our hooks.server.ts file, and whip up some boilerplate (which, to be honest, is mostly copied right from the docs).

import { GOOGLE_AUTH_CLIENT_ID, GOOGLE_AUTH_SECRET, AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, DYNAMO_AUTH_TABLE, AUTH_SECRET } from "$env/static/private";

import { DynamoDB, type DynamoDBClientConfig } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
import { DynamoDBAdapter } from "@next-auth/dynamodb-adapter";
import type { Adapter } from "@auth/core/adapters";

const dynamoConfig: DynamoDBClientConfig = {
  credentials: {
    accessKeyId: AMAZON_ACCESS_KEY,
    secretAccessKey: AMAZON_SECRET_KEY,
  },

  region: "us-east-1",
};

const client = DynamoDBDocument.from(new DynamoDB(dynamoConfig), {
  marshallOptions: {
    convertEmptyValues: true,
    removeUndefinedValues: true,
    convertClassInstanceToMap: true,
  },
});

and now we add our adapter to our auth config:

  adapter: DynamoDBAdapter(client, { tableName: DYNAMO_AUTH_TABLE }),

and now, after logging out, and logging back in, we should see some entries in our DynamoDB instance

Authentication hooks

The auth-core package provides a number of callbacks you can hook into, if you need to do some custom processing.

The signIn callback is invoked, predictably, after a successful login. It’s passed an account object from whatever provider was used, Google in our case. One use case with this callback could be to optionally look up, and sync legacy user metadata you might have stored for your users before switching over to OUath authentication with established providers.

async signIn({ account }) {
  const userSync = await getLegacyUserInfo(account.providerAccountId);
  if (userSync) {
    account.syncdId = userSync.sk;
  }

  return true;
},

The jwt callback gives you the ability to store additional info in the authentication token (you can use this regardless of whether you’re using a database adapter). It’s passed the (possibly mutated) account object from the signIn callback.

async jwt({ token, account }) {
  token.userId ??= account?.syncdId || account?.providerAccountId;
  if (account?.syncdId) {
    token.legacySync = true;
  }
  return token;
}

We’re setting a single userId onto our token that’s either the syndId we just looked up, or the providerAccountId already attached to the provider account. If you’re curious about the ??= operator, that’s the nullish coalescing assignment operator.

Lastly, the session callback gives you an opportunity to shape the session object that’s returned when your application code calls locals.getSession()

async session({ session, user, token }: any) {
  session.userId = token.userId;
  if (token.legacySync) {
    session.legacySync = true;
  }
  return session;
}

now our code could look for the legacySync property, to discern that a given login has already sync’d with a legacy account, and therefore know not to ever prompt the user about this.

Extending the types

Let’s say we do extand the default session type, like we did above. Let’s see how we can tell TypeScript about the things we’re adding. Basically, we need to use a TypeScript feature called interface merging. We essentially re-declare an interface that already exists, add stuff, and then TypeScript does the grunt work of merging (hence the name) the original type along with the changes we’ve made.

Let’s see it in action. Go to the app.d.ts file SvelteKit adds to the root src folder, and add this

declare module "@auth/core/types" {
  interface Session {
    userId: string;
    provider: string;
    legacySync: boolean;
  }
}

export {};

We have to put the interface in the right module, and then we add what we need to add.

Note the odd export {}; at the end. There has to be at least one ESM import or export, so TypeScript treats the file correctly. SvelteKit by default adds this, but make sure it’s present in your final product.

Wrapping up

We’ve covered a broad range of topics in this post. We’ve seen how to set up Auth.js in a SvelteKit project using the @auth/core library. We saw how to set up providers, adapters, and then took a look at various callbacks that allow us to customize our authentication flows.

Best of all, the tools we saw will work with SvelteKit or Next, so if you’re already an experienced Next user, a lot of this was probably familiar. If not, much of what you saw will be portable to Next if you ever find yourself using that.

]]>
https://frontendmasters.com/blog/using-nextauth-now-auth-js-with-sveltekit/feed/ 0 1764