nextjs-rewrite (#5)
Reviewed-on: #5 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 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;
|
||||
Reference in New Issue
Block a user