How can I use Better Auth with a Node.js Express backend and a separate Next.js frontend?
I’m building an application where the backend is a standalone Node.js + Express server, and the frontend is a separate Next.js app. I’d like to integrate Better Auth for authentication and user management across both.
How can I properly configure Better Auth so that:
- The Express backend handles authentication logic and token validation securely.
- The Next.js frontend can interact with the backend for login, signup, and session management.
- Authentication state (like JWT or session cookies) is maintained between the two apps, even though they run on different domains or ports.
What’s the recommended setup for this architecture — including configuration examples, best practices, and potential pitfalls when separating frontend and backend?
How can I properly configure Better Auth so that:
- The Express backend handles authentication logic and token validation securely.
- The Next.js frontend can interact with the backend for login, signup, and session management.
- Authentication state (like JWT or session cookies) is maintained between the two apps, even though they run on different domains or ports.
What’s the recommended setup for this architecture — including configuration examples, best practices, and potential pitfalls when separating frontend and backend?
2 Replies
So you can use Better Auth for both frontend and backend , Im actually using it currently for my React app and Express backend. You can follow the docs to get the auth client for your next.js app, and you can access Better Auth APIs using the betterAuth object on the Express side. Just make sure to mount the handler if you want to use Better Auth's default APIs in your Express backend. If not, you can skip it and utilize the methods in auth.api object to create your own custom endpoints. You can even create plugins.......make sure to add the OpenAPI plugin to view Scalar documentation for your Better Auth endpoints any plugins you add will be displayed in the Scalar docs with their endpoints. Most importantly, make sure to configure CORS accordingly to exchange cookies between your Next.js frontend and Express backend, since they're on different domains/ports. Set credentials: true and specify allowed origins explicitly, otherwise authentication won't work across the two apps.
Thanks.
Can you share the example code?