43 lines
1010 B
TypeScript
43 lines
1010 B
TypeScript
const CSRF_COOKIE_NAME = "csrf_token";
|
|
const CSRF_HEADER_NAME = "X-CSRF-Token";
|
|
|
|
function readCookie(name: string): string | undefined {
|
|
if (typeof document === "undefined") {
|
|
return undefined;
|
|
}
|
|
|
|
const cookies = document.cookie.split(";");
|
|
for (const cookie of cookies) {
|
|
const [rawName, ...rest] = cookie.trim().split("=");
|
|
if (rawName !== name) {
|
|
continue;
|
|
}
|
|
const rawValue = rest.join("=");
|
|
if (!rawValue) {
|
|
return undefined;
|
|
}
|
|
try {
|
|
return decodeURIComponent(rawValue);
|
|
} catch {
|
|
return rawValue;
|
|
}
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
|
|
export function getCsrfToken(): string | undefined {
|
|
const token = readCookie(CSRF_COOKIE_NAME)?.trim();
|
|
return token ? token : undefined;
|
|
}
|
|
|
|
export function withCsrfHeaders(headers?: HeadersInit): Headers {
|
|
const next = new Headers(headers ?? {});
|
|
const csrfToken = getCsrfToken();
|
|
if (csrfToken && !next.has(CSRF_HEADER_NAME)) {
|
|
next.set(CSRF_HEADER_NAME, csrfToken);
|
|
}
|
|
return next;
|
|
}
|
|
|