Validate Client Side Auth On Server

Hi. I have a basic SPA written in react with a client side auth object to handle auth. Now i have other routes on my backend (with the auth server) which are used for different parts of the web app. How can i make sure the user is authenticated on the server for these routes. any help would be appreciated, and sorry if there is a straight forward answer but i couldn't find it. (Unless thats what a server useSession is for??) Here is the code for the routes in question and the auth logic (taken from the get started docs) Routes:
app.all("/api/auth/*", toNodeHandler(auth));
app.get("/api/v1/recipe/:videoId", recipeHandler);
app.post("/api/v1/video", downloadHandler)
app.all("/api/auth/*", toNodeHandler(auth));
app.get("/api/v1/recipe/:videoId", recipeHandler);
app.post("/api/v1/video", downloadHandler)
Auth Logic:
export const dialect = new BunWorkerDialect({
url: "./sqlite.db",
});
export const auth = betterAuth({
database: dialect,
emailAndPassword: {
enabled: true,
}
})
export const dialect = new BunWorkerDialect({
url: "./sqlite.db",
});
export const auth = betterAuth({
database: dialect,
emailAndPassword: {
enabled: true,
}
})
Solution:
you can use the export auth to make calls like auth.api.getSession that you will pass the original request headers to, here is a NextJS but it will work on any framework (you will need to handle the headers differently based on your framework) ```ts import { auth } from '@/lib/auth'; import { headers } from 'next/headers';...
Jump to solution
3 Replies
Solution
lonelyplanet
lonelyplanet2w ago
you can use the export auth to make calls like auth.api.getSession that you will pass the original request headers to, here is a NextJS but it will work on any framework (you will need to handle the headers differently based on your framework)
import { auth } from '@/lib/auth';
import { headers } from 'next/headers';

const session = await auth.api.getSession({
headers: await headers(),
});

if (session) console.log('im logged in');
else console.log('im not logged in');
import { auth } from '@/lib/auth';
import { headers } from 'next/headers';

const session = await auth.api.getSession({
headers: await headers(),
});

if (session) console.log('im logged in');
else console.log('im not logged in');
lonelyplanet
lonelyplanet2w ago
see more documentation here
API | Better Auth
Better Auth API.
KwozyK
KwozyKOP2w ago
Thanks wasn’t sure just wanted to confirm. Appreciate it

Did you find this page helpful?