Svelte

You can use the Stytch Vanilla JavaScript SDK headless methods and prebuilt UI components with your Svelte app. Here's an example of how you might implement auth using Stytch's UI components.

Create some context utils and a StytchUIClient:

// utils.ts
import { StytchUIClient } from '@stytch/vanilla-js';
import { getContext, setContext } from "svelte";

const STYTCH_PUBLIC_TOKEN = import.meta.env.VITE_STYTCH_PUBLIC_TOKEN;

const StytchContextKey = {};

export const setStytchClient = (client: StytchUIClient) =>
  setContext(StytchContextKey, { client });

export const getStytchClient = (): StytchUIClient | null => {
  const cli = getContext<undefined | { client: StytchUIClient }>(
    StytchContextKey
  );
  return cli?.client || null;
};

import { browser } from '$app/environment';

export const stytch = new StytchUIClient(STYTCH_PUBLIC_TOKEN, {
    cookieOptions: {
      jwtCookieName: `stytch_session_jwt`,
      opaqueTokenCookieName: `stytch_session`,
    },
});

Create a StytchContext component and use it in your main layout:

// StytchContext.svelte
<script lang="ts">
  import type { StytchUIClient } from "@stytch/vanilla-js";
  import { setStytchClient } from "./utils";

  export let client: StytchUIClient;
  setStytchClient(client);
</script>

<slot />
// +layout.svelte
<main>
	<StytchContext client={stytch}>
		<slot />
	</StytchContext>
</main>

Create a StytchLogin component:

<script lang="ts">
  import { onMount } from "svelte";
  import { getStytchClient } from "./utils";
  import type {
    Callbacks,
    StytchLoginConfig,
    StyleConfig,
  } from "@stytch/vanilla-js";

  export let stytchClient = getStytchClient();
  export let config: StytchLoginConfig;
  export let styles: StyleConfig | undefined = undefined;
  export let callbacks: Callbacks | undefined = undefined;

  let containerEl: HTMLDivElement;

  onMount(() => {
    stytchClient?.mountLogin({
      config,
      callbacks,
      elementId: '#elementId',
      styles,
    });
  });
</script>

<div bind:this={containerEl} />

Use the login component on your main page:

// +page.svelte
<section>
  <h1>
    Welcome to your new<br />SvelteKit app
  </h1>
  <StytchLogin config={StytchConfig} />
</section>