Client-side Reference

Browser-side Vue composables and fetch utilities for session state, magic link handling, authenticated requests, and CSRF token reading.

These functions ship from the auth-h3client/client entry point and run in the browser (or during Vue SSR) of any Nuxt or Vue application. When using the Nuxt module, they are auto-imported in components and pages. Outside the Nuxt module, import them explicitly:

import { useAuthData, useMagicLink, executeRequest, getCsrfToken } from 'auth-h3client/client'

The composables depend on nuxt/app for SSR context composables (useState, useRequestHeaders, useRequestEvent, useFetch), so they require an application that provides those symbols.


useAuthData(authStatusUrl?)

Returns a reactive Ref<AuthState> representing the current authentication state. Implements a singleton pattern using useState('auth') to prevent duplicate network requests during SSR and hydration.

const auth = await useAuthData()

On the server, it forwards all incoming request headers to the auth status endpoint and captures Set-Cookie response headers to forward them to the browser. On the client, it reuses the server-populated payload from the SSR hydration cache for the first call, then fetches fresh data on subsequent calls.

Parameters

ParameterTypeDefaultDescription
authStatusUrlstring'/api/auth/users/authStatus'Endpoint path for the auth status check when you use the Nuxt module. In manual H3 or Nitro setups, pass the path where you registered getAuthStatusHandler.

Return type

interface AuthState {
  authorized: boolean
  mfaRequired: boolean
  id?: string       // userId from the IAM response
  message?: string  // MFA challenge message when mfaRequired is true
}

Status code handling

StatusauthorizedmfaRequiredNotes
200truefalseUser is authenticated
202falsetrueMFA challenge; message contains instructions
401falsefalseNot authenticated
Any errorfalsefalseNetwork or server error; fails silently

useMagicLink(path?)

Reads magic link query parameters from the current route, validates that all required parameters are present, and calls the appropriate server API endpoint based on the reason parameter. See Client-Side MFA for the full bounce-route integration.

const result = await useMagicLink()

Throws a Nuxt 404 error if any required query parameter (random, token, reason, visitor) is missing, if no API endpoint matches the reason, or if the server returns an error.

Parameters

ParameterTypeDescription
pathstringCustom API endpoint for non-standard reason values

Routing by reason

reason valueEndpoint called
MAGIC_LINK_MFA_CHECKSGET /api/auth/verify-mfa
PASSWORD_RESETGET /api/auth/reset-password
change_emailGET /api/auth/update-email
Any other valuepath argument

Return type

{
  reason: string                                    // The reason from the link
  link: 'Password Reset' | 'MFA Code' | 'Custom MFA'
  token: string
  random: string
  visitor: string
}

executeRequest<T>(url, method, body?, customHeaders?, customOptions?, context?)

Universal fetch wrapper for making authenticated requests. Automatically injects the CSRF token on the client and proxies request headers on the server. Captures Set-Cookie response headers and forwards them to the browser.

const result = await executeRequest<{ name: string }>('/api/profile', 'GET')

if (result.ok) {
  console.log(result.data.name)
}

Parameters

ParameterTypeDescription
urlstringEndpoint URL
method'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH'HTTP method
bodyobjectRequest body for POST/PUT/PATCH, or query parameters for GET
customHeadersRecord<string, string>Additional headers
customOptionsFetchOptionsAdditional ofetch options
contextApiContextServer-side context with event, fetcher, and headers

Return type

type Results<T> =
  | { ok: true; data: T; date: string }
  | { ok: false; reason: string; date: string }

On the client, X-CSRF-Token is injected automatically from getCsrfToken(). On the server, incoming request headers are proxied when context.headers is provided.

Server-side usage

server/api/proxy.get.ts
export default defineAuthenticatedEventHandler(async (event) => {
  const result = await executeRequest<Data>(
    '/api/downstream',
    'GET',
    {},
    {},
    {},
    {
      headers: useRequestHeaders(),
      event,
      fetcher: useRequestFetch()
    }
  )
  return result
})

getCsrfToken()

Reads the __Host-csrf cookie from document.cookie and returns the first segment (the raw token before the first .). Returns undefined if the cookie is not present.

This function is browser-only. On the server, the CSRF token is injected by executeRequest from the forwarded request headers.

const token = getCsrfToken()

// Manual header injection:
fetch('/api/action', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': token ?? '',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ ... })
})

Use getCsrfToken directly only when making raw fetch calls. For everything else, use executeRequest, which handles token injection automatically. See CSRF Protection for the double-submit pattern this composable integrates with.

Logo