Docs

Nuxt Integration

Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.

Create API Route

We need to mount the handler to an API route. Create a file inside /server/api called [...auth].ts and add the following code:

server/api/[...auth].ts
import { auth } from "~/utils/auth.config";
 
export default defineEventHandler((event) => {
	return auth.handler(toWebRequest(event));
});

You can change the path on your better-auth configuration but it's recommended to keep it as /api/[...auth]

Migrate the database

Run the following command to create the necessary tables in your database:

npx @better-auth/cli migrate

Create a client

Create a client instance. You can name the file anything you want. Here we are creating client.ts file inside the lib/ directory.

client.ts
import { createAuthClient } from "better-auth/vue" // make sure to import from better-auth/vue
 
export const authClient = createAuthClient({
    //you can pass client configuration here
})

Once you have created the client, you can use it to sign up, sign in, and perform other actions. Some of the actions are reactive.

Example usage

index.vue
<script setup lang="ts">
import { authClient } from "~/lib/client"
const session = authClient.useSession()
</script>
 
<template>
    <div>
        <button v-if="!session?.data" @click="() => client.signIn.social({
            provider: 'github'
        })">
            Continue with github
        </button>
        <div>
            <pre>{{ session.data }}</pre>
            <button v-if="session.data" @click="client.signOut()">
                Sign out
            </button>
        </div>
    </div>
</template>

SSR Usage

If you are using Nuxt with SSR, you can use the useSession function in the setup function of your page component and pass useFetch to make it work with SSR.

index.vue
<script setup lang="ts">
import { authClient } from "~/lib/auth-client";
 
const { data: session } = authClient.useSession(useFetch);
</script>
 
<template>
    <p>
        {{ session }}
    </p>
</template>

Middleware

To add middleware to your nuxt project, you can use the useSession method from the client.

middleware/auth.global.ts
import { authClient } from "~/lib/auth-client"l
export default defineNuxtRouteMiddleware(async (to, from) => {
	const { data: session } = await authClient.useSession(useFetch); 
	if (!session.value) {
		if (to.path === "/dashboard") {
			return navigateTo("/");
		}
	}
});

On this page

Edit on GitHub