#How to get auth.api instance

4 messages · Page 1 of 1 (latest)

zealous sigilBOT
#

Hi @gritty parcel. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To get the auth.api instance with Better Auth and Convex, you need to use the getAuth() method from the component client. Here's how to do it:

Getting auth.api Instance

In your Convex functions, use the authComponent.getAuth() method to get both the auth object (which contains auth.api) and headers:

import { mutation } from "./_generated/server";
import { v } from "convex/values";
import { createAuth, authComponent } from "./auth";

export const updateUserPassword = mutation({
  args: {
    currentPassword: v.string(),
    newPassword: v.string(),
  },
  handler: async (ctx, args) => {
    const { auth, headers } = await authComponent.getAuth(createAuth, ctx);
    await auth.api.changePassword({
      body: {
        currentPassword: args.currentPassword,
        newPassword: args.currentPassword,
      },
      headers,
    });
  },
});

The getAuth() method provides both the auth object (which includes auth.api) and the necessary headers for authentication. Many Better Auth server methods require headers to be passed in so session cookies can be parsed and validated. Basic Usage

With Local Install

The same approach works with Local Install. The key difference with local install is that you have more control over your schema and can use additional plugins, but the way you access auth.api remains the same - through authComponent.getAuth(createAuth, ctx).

#

The knowledge sources don't explicitly mention any special considerations for accessing auth.api specifically with the admin plugin in a local install setup, but the pattern shown above should work consistently across different plugin configurations.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@gritty parcel Kapa.ai is still learning and improving, please let me know how I did by reacting below.