newbie: are my conventions for checking if a user is logged in on client and server side fine?

hi so this is my first time rolling my own auth. ive used clerk before. the db im using with better auth is mongodb as my user data is there rn. We only need google auth (no email/password). I've gone through the installation and setup and ive got google user logins registering in my mongodb collection. The question I have is, am I properly checking if the users logged in (client and server side)? for the client side, i made a "client-auth-guard" component that basically checks it. So is it fine if I use this component for the client side: https://gist.github.com/navincodesalot/e3fcd7581d92ae51ea1602cdb4ffe943 For server side checking if user is logged in, Iwould I have to use server actions? (https://www.better-auth.com/docs/integrations/next#rsc-and-server-actions) but then how would the server side look like on a route handler? (my post, get, etc endpoints) My middleware.ts: (follows a clerk pattern) https://gist.github.com/navincodesalot/2f2d016202d298cafa7c3925a047e71c Just wanted to know if I am approaching the checking on client and server side properly thanks. (Also I feel it’s a bit slow when checking if a user is logged in or not. And when I use my middleware to redirect users if they access locked routes, it’s chunky and slow. Is it cause it’s a dev server?)
Gist
client-auth-guard.tsx
GitHub Gist: instantly share code, notes, and snippets.
Gist
middleware.ts
GitHub Gist: instantly share code, notes, and snippets.
Next.js integration | Better Auth
Integrate Better Auth with Next.js.
2 Replies
bekacru
bekacru4w ago
For guarding routes, use middleware to redirect users - but don’t fetch the session in the middleware, just rely on cookies (there’s an example in our Next.js integration docs). For protecting pages, fetch the session in an RSC component and decide what to render based on that. Regarding performance, make sure to use cookies in the middleware (without fetching the session), enable cookie cache, and make sure to proper DB indexes (explore optimization methods from the docs) https://www.better-auth.com/docs/guides/optimizing-for-performance
Optimizing for Performance | Better Auth
A guide to optimizing your Better Auth application for performance.
Elite
EliteOP3w ago
Sorry for the late reply, will check this out. Thank you! Also is my middleware fine for defining public routes and etc

Did you find this page helpful?