Docs

API

When you create a new Better Auth instance, it gives you an api object. This object provides functions to interact with the server while your code is running server-side. You can use these functions to call any API endpoint on the server.

Any endpoint added to Better Auth, whether from plugins or the core, will be accessible through the api object.

Calling API Endpoints on the Server

To call an API endpoint on the server, import your auth instance and call the endpoint using the api object.

server.ts
import { betterAuth } from "better-auth";
import { headers } from "next/headers";
 
export const auth = betterAuth({
    //...
})
 
// calling get session on the server
await auth.api.getSession({
    headers: headers()
})

Unlike the client, the server needs the values to be passed as an object with the key body for the body, headers for the headers, and query for the query.

server.ts
await auth.api.signInEmail({
    body: {
        email: "",
        password: ""
    }
})

Better auth API endpoints are built on top of better-call, a tiny web framework that lets you call REST API endpoints as if they were regular functions and allows us to easily infer client types from the server.

Getting the Response Object

When you invoke an API endpoint on the server, it will return a standard JavaScript object or array directly. To get the Response object instead, you can use the asResponse option.

server.ts
const response = await auth.api.signInEmail({
    body: {
        email: "",
        password: ""
    },
    asResponse: true
})

Error Handling

When you call an API endpoint in the server, it will throw an error if the request fails. You can catch the error and handle it as you see fit. The error instance is an instance of APIError.

server.ts
import { APIError } from "better-auth/api";
 
try {
    await auth.api.signInEmail({
        body: {
            email: "",
            password: ""
        }
    })
} catch (error) {
    if (error instanceof APIError) {
        console.log(error.message, error.status)
    }
}

On this page

Edit on GitHub