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:
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:
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.
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
Server Usage
The api
object exported from the auth instance contains all the actions that you can perform on the server. Every endpoint made inside Better Auth is a invocable as a function. Including plugins endpoints.
Example: Getting Session on a server API route
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.
Middleware
To add middleware to your Nuxt project, you can use the useSession
method from the client.
Resources & Examples
- Nuxt and Nuxt Hub example on GitHub.
- NuxtZzle is Nuxt,Drizzle ORM example on github preview
- Nuxt example on StackBlitz.