getCsrfToken

Browser-only helper that reads the __Host-csrf cookie and returns the raw token segment so custom fetch calls can inject the X-CSRF-Token header manually.

getCsrfToken is a low-level helper for reading the CSRF token out of document.cookie. Use it when you are making a raw fetch call that cannot go through executeRequest (for example, integrating with a third-party SDK that takes its own header object). For every other case, prefer executeRequest, which handles CSRF injection automatically.

import { getCsrfToken } from 'auth-h3client/client'

const token = getCsrfToken()

Signature

function getCsrfToken(): string | undefined

The function reads the __Host-csrf cookie from document.cookie, splits off the first segment before the first ., and returns the raw token. It returns undefined when the cookie is absent (for example, before the first request reaches the gateway, or after logout).

The signed cookie format is base64(token).base64(keyword).expiry.hmac. getCsrfToken only returns the first segment because that is the value the gateway expects as the X-CSRF-Token request header.


Browser-only

This function reads document.cookie directly, so it only works in a browser context. During Vue SSR, there is no document object and the call will throw. If you need to build an authenticated request during SSR, use executeRequest with an ApiContext instead: it forwards incoming request headers so the upstream call receives the cookie naturally.


Manual fetch example

const token = getCsrfToken()

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

If token is undefined, the request will fail the CSRF check on the gateway with a 403 response. That is the expected behavior: the browser cannot recover a missing CSRF cookie on its own. Send the user back through a route that issues the cookie (any route under the global middleware chain issues it via generateCsrfCookie).

See CSRF Protection for the full lifecycle of the cookie and the verification contract on the server side.

Logo