Refactor
This commit is contained in:
35
lib/server-service.ts
Normal file
35
lib/server-service.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
/**
|
||||
* Server-side fetch wrapper with authentication.
|
||||
*/
|
||||
export async function fetchServer<T = unknown>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const cookieStore = cookies();
|
||||
const authToken = cookieStore.get('Authorization')?.value;
|
||||
|
||||
if (!authToken) redirect('/login');
|
||||
|
||||
try {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
...options.headers,
|
||||
},
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (res.status === 401) redirect('/login');
|
||||
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
|
||||
|
||||
return res.json();
|
||||
} catch (error) {
|
||||
console.error(`Server request to ${endpoint} failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user