Skip to content

Auth Client

The Feathers Cloud Auth client in the @featherscloud/auth package is used to manage device and user identities as well as access tokens.

Installation

It can be installed with

sh
npm i @featherscloud/auth
pnpm add @featherscloud/auth
yarn add @featherscloud/auth
bun add @featherscloud/auth

Initialization

In any web application, create an 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

Authenticated requests to a server running one of the supported platforms can be made like this:

ts
import { authFetch } from './auth.js'

async function getMessage() {
  // 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()

  return body
}

Frameworks

For complete examples for different frontend frameworks see the following pages: