blob: ebfb6920e61fc1019fa778b34e211133cbfb6e85 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
export function getCookie(name: string): string | undefined {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift();
}
/**
* A wrapper around fetch that automatically includes the CSRF token
* for state-changing requests (POST, PUT, DELETE).
*/
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const method = init?.method?.toUpperCase() || 'GET';
const isStateChanging = ['POST', 'PUT', 'DELETE'].includes(method);
const headers = new Headers(init?.headers || {});
if (isStateChanging) {
const token = getCookie('csrf_token');
if (token) {
headers.set('X-CSRF-Token', token);
}
}
// Ensure requests are treated as coming from our own origin if needed,
// but for a same-origin API, standard fetch defaults are usually fine.
return fetch(input, {
...init,
headers,
credentials: 'include', // Ensure cookies are sent
});
}
|