123df671f5
Reviewed-on: #5 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
/**
|
|
* Server-side session helper for Better Auth
|
|
* This provides getSession() for use in server components
|
|
*/
|
|
|
|
import { cookies } from "next/headers";
|
|
|
|
export async function getSession() {
|
|
try {
|
|
const cookieStore = await cookies();
|
|
|
|
// Get the session token from cookies
|
|
const sessionToken = cookieStore.get('better-auth.session_token');
|
|
|
|
if (!sessionToken) {
|
|
return null;
|
|
}
|
|
|
|
// Make a request to the Better Auth API to get the session
|
|
// This is the standard way Better Auth handles session verification
|
|
// Use disableCookieCache to bypass the cookie cache and get fresh data from the database
|
|
const response = await fetch(`${process.env.BETTER_AUTH_URL || 'http://localhost:3000'}/api/auth/get-session?disableCookieCache=true`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Cookie': `${sessionToken.name}=${sessionToken.value}`
|
|
},
|
|
cache: 'no-store',
|
|
});
|
|
|
|
if (!response.ok) {
|
|
return null;
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('Failed to get session:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// For backward compatibility with existing code
|
|
export type AuthUser = {
|
|
user: {
|
|
id: string;
|
|
email: string;
|
|
name?: string;
|
|
role?: string;
|
|
[key: string]: any;
|
|
};
|
|
session: {
|
|
token: string;
|
|
expiresAt: Date;
|
|
[key: string]: any;
|
|
};
|
|
} | null;
|