balls
This commit is contained in:
47
lib/server-utils.ts
Normal file
47
lib/server-utils.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
/**
|
||||
* Fetch API with Authorization (for server-side usage only).
|
||||
* @param endpoint - The API endpoint.
|
||||
* @param options - Fetch options (optional).
|
||||
* @returns Parsed JSON response.
|
||||
*/
|
||||
export async function fetchWithAuthorization<T = unknown>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
// Access the Authorization cookie securely
|
||||
const cookieStore = await cookies();
|
||||
const authToken = cookieStore.get("Authorization")?.value;
|
||||
|
||||
console.log("authToken", authToken);
|
||||
|
||||
if (!authToken) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
const config: RequestInit = {
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
...(options.headers || {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
};
|
||||
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, config);
|
||||
|
||||
if (res.status === 401) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch ${endpoint}: ${res.statusText}`);
|
||||
}
|
||||
|
||||
const data = await res.json() as T;
|
||||
|
||||
return data as Promise<T>;
|
||||
}
|
||||
Reference in New Issue
Block a user