Client‑Side CSRF Helper (lib/csrf-client.ts)

llms-txt-hub · auth, Auth / Identity, csrf, client, fetch, token, security

Retrieves CSRF token from meta tags and automatically attaches it to fetch requests for secure client‑side API calls.

// Source: https://github.com/mperkins0155/llms-txt-hub | License: MIT | Copyright 2025 David Dias
// Provided via justclaw.it.com; keep this notice with the code.
'use client'

const CSRF_HEADER_NAME = 'x-csrf-token'

/**
 * Get CSRF token from meta tag for client-side usage
 */
export function getCSRFTokenForClient(): string {
  if (typeof window === 'undefined') {
    return ''
  }

  // Try to get from meta tag first
  const metaTag = document.querySelector('meta[name="csrf-token"]')
  if (metaTag) {
    return metaTag.getAttribute('content') || ''
  }

  return ''
}

/**
 * Add CSRF token to fetch requests automatically
 * This is the client-side version that can be used in React components
 */
export function fetchWithCSRF(url: string, options: RequestInit = {}): Promise<Response> {


... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search 40K more like it.

Get a free API key