Defines API base URL and retrieves authentication token for authenticated requests to the backend.
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api";
function getToken(): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem("prospex_token");
}
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const token = getToken();
const res = await fetch(`${API_URL}${path}`, {
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options?.headers,
},
...options,
});
if (res.status === 401) {
if (typeof window !== "undefined") {
localStorage.removeItem("prospex_token");
localStorage.removeItem("prospex_user");
window.location.href = "/login";
}
throw new Error("Unauthorized");
}
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key