Skip to content

Svelte

Initialization

In your Svelte application, create a src/auth.ts file that allows to make authenticated requests to the backend like this:

ts
import { createClient, LoginRequiredError } from '@featherscloud/auth'

export const appId = '<your-app-id>'

export const auth = createClient({ appId })

/**
 * Make an authenticated request using the fetch API or
 * redirect to the login page if the user needs to log in.
 * 
 * @param url The URL for the request
 * @param options Additional request options.
 * @returns The fetch response
 */
export async function authFetch(url: string, options?: RequestInit) {
  const headers = new Headers(options?.headers)

  try {
    // Set the authorization header with the Feathers Cloud Auth token
    headers.set('Authorization', await auth.getHeader())
  } catch (error) {
    if (error instanceof LoginRequiredError) {
      // Redirect to login page if a login is required
      window.location.href = await auth.getLoginUrl(error)
    } else {
      // Throw any other error
      throw error
    }
  }

  return fetch(url, {
    ...options,
    headers
  })
}

This file exports an authFetch function that can be used just like the normal fetch API and will redirect to the login page if the user needs to log in.

Usage

A Svelte component using the Auth client and loading the message from one of the platform example servers looks like this:

svelte
<script lang="ts">
  import { authFetch } from './auth';

  let message = '';

  async function loadMessage() {
    // Get data with authentication from your server
    const response = await authFetch('http://localhost:3030/message', {
      method: 'GET'
    });

    if (response.status >= 400) {
      throw new Error(`Failed to load message: ${response.statusText}`);
    }

    const body = await response.json();

    message = body.message;
  }

  loadMessage().catch((error: any) =>
    alert(`There was an error: ${error.message}`)
  );
</script>

<main>
  <h1>Feathers Cloud Svelte Demo</h1>
  <p>The message from the server is:</p>
  <h2>{message}</h2>
</main>

You can find the full Vite + Svelte example application here.