NuxtN
Nuxt5mo ago
22 replies
JJ

How to integrate better-auth library with Nuxt 4

I have configured better-auth on my Hono server and am now trying to set up authentication on my frontend that is on a separate port than the server. I currently have the auth-client set up as a plugin:
#plugins/auth-client.ts
import { createAuthClient } from "better-auth/vue";

export default defineNuxtPlugin({
    name: "authClient",
    parallel: true,
    async setup() {
        const config = useRuntimeConfig();
        const authClient = createAuthClient({
            baseURL: config.public.backendUrl,
            fetchOptions: {
                credentials: "include",
            },
        });
        // Provide it globally
        return {
            provide: {
                authClient,
            },
        };
    },
});


And I can succesfully use it in my login page.
Alongisde the auth-client I also set up a middleware to protect the users from accessing /dashboard routes when they are not signed in. The middleware currently looks like this:
# middleware/auth.global.ts
// Guard dashboard routes from invalid sessions
export default defineNuxtRouteMiddleware(async (to) => {
    const { $authClient } = useNuxtApp();
    const { data: session } = await $authClient.useSession(useFetch);
    if (!session.value) {
        if (to.path === "/dashboard") {
            return navigateTo("/auth/login");
        }
    }
});


No in my login page when the customer submits the login form then I send out
const { $authClient } = useNuxtApp();
$authClient.signIn.email

and navigate the user to /dashboard on success

The problem I am running into is that when the user succesfully submit the form I am redirected back to /auth/login for some reason. The user never reaches /dashboard
Was this page helpful?