Get session data on first load (nextjs + elysia)
Is there a way to retrieve the session data on the first load using useSession? I already using middleware to validate the session. For my pages, I want to display the user data immediately without showing the loading.
2 Replies
you can try to retrive the session first on the server
// middleware
import { NextRequest, NextResponse } from 'next/server';
import { betterFetch } from '@better-fetch/fetch';
import type { auth } from '../backend/src/utils/auth/auth';
type Session = typeof auth.$Infer.Session;
export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<Session>(
'http://localhost:3000/api/auth/get-session',
{
baseURL: request.nextUrl.origin,
headers: {
cookie: request.headers.get('cookie') || '',
},
}
);
if (!session) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/stores'],
};
// StoresLayout
export default function StoresLayout() {
const links = mockdata.map((item) => <LinksGroup {...item} key={item.label} />);
const { data } = authClient.useSession();
console.log({ data });
just wondering does it has the function like react query thn can prefetch first so the data will directly available on the hook