Handles Cross-Site Request Forgery (CSRF) token management for secure API requests.
Funky.CSRF provides utilities for retrieving and injecting CSRF tokens into API requests. It's primarily used internally by Funky.Api, but can be used directly for custom fetch requests.
Get CSRF token from the browser cookie.
Returns: string|null - The CSRF token or null if not found
Example:
const token = Funky.CSRF.getToken();
if (token) {
console.log('Token available');
} else {
console.log('User may need to log in');
}Enhanced fetch wrapper with automatic CSRF token injection.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
| url | string | Yes | The URL to fetch |
| options | object | No | Standard fetch options |
Returns: Promise<Response> - Fetch promise
Example:
const response = await Funky.CSRF.secureFetch('/api/trades', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ quantity: 100 })
});Store CSRF token (called after login). Note: Token is automatically stored as a cookie by the server.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
| token | string | Yes | The CSRF token |
- Token Storage: The server sets the CSRF token as an HttpOnly cookie named
csrf_token - Token Injection: For POST, PUT, DELETE, PATCH requests, the token is added to the
X-CSRF-Tokenheader - Token Validation: Server validates the header matches the cookie
- Expiry Handling: If token validation fails (403), user may need to re-login
1. User logs in
↓
2. Server sets csrf_token cookie
↓
3. JS reads token from cookie
↓
4. JS adds X-CSRF-Token header to requests
↓
5. Server validates token matches cookie
None - this is a core module.
// Usually you'd use Funky.Api, but for custom needs:
const response = await Funky.CSRF.secureFetch('/api/custom-endpoint', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: 'value' })
});
const json = await response.json();function checkAuth() {
const token = Funky.CSRF.getToken();
if (!token) {
window.location.href = '/auth/login';
return false;
}
return true;
}- CSRF token is required for all state-changing operations (POST, PUT, DELETE, PATCH)
- GET requests don't require CSRF tokens
- Token mismatch results in 403 Forbidden response
- Always use
Funky.ApiorFunky.CSRF.secureFetchfor API calls