[GH-ISSUE #1131] Organization Hooks aren't Typed #8609

Closed
opened 2026-04-13 03:43:39 -05:00 by GiteaMirror · 25 comments
Owner

Originally created by @msywulak on GitHub (Jan 4, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/1131

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Add the organization plugin to your config

  plugins: [openAPI(), passkey(), nextCookies(), organization(), adminPlugin()],

add organizationClient to your client

export const authClient = createAuthClient({
  plugins: [
    passkeyClient(),
    magicLinkClient(),
    organizationClient(),
    adminClient(),
  ],
});

add to your auth

import { betterAuth } from "better-auth";
import { authConfig } from "@/lib/auth/config";
import { authActions } from "@/lib/auth/actions";

export const auth = betterAuth({
  ...authConfig,
  ...authActions,
});

Current vs. Expected behavior

Currently the following hooks are Any typed. I would expect them to have the appropriate types for the organization plugin.

image

What version of Better Auth are you using?

1.1.9

Provide environment information

- Windows 11

Which area(s) are affected? (Select all that apply)

Types

Auth config (if applicable)

import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/db";
import {
  openAPI,
  organization,
  admin as adminPlugin,
} from "better-auth/plugins";
import { passkey } from "better-auth/plugins/passkey";
import { APP_NAME } from "@/utils/constants";
import { env } from "@/env";
import { BetterAuthOptions } from "better-auth";
import { nextCookies } from "better-auth/next-js";

export const authConfig = {
  appName: APP_NAME,
  baseURL:
    env.NODE_ENV === "production"
      ? env.NEXT_PUBLIC_APP_URL
      : "http://app.localhost:3000",
  trustedOrigins: [
    env.NEXT_PUBLIC_APP_URL,
    "http://app.localhost:3000",
    "http://localhost:3000",
  ],
  logger: {
    disabled: env.NODE_ENV === "production",
    level: "debug",
  },
  database: drizzleAdapter(db, {
    provider: "pg",
  }),
  session: {
    freshAge: 0,
    expiresIn: 60 * 60 * 24 * 3, // 3 days
    updateAge: 60 * 60 * 12, // 12 hours (every 12 hours the session expiration is updated)
    cookieCache: {
      enabled: true,
      maxAge: 60 * 5, // 5 minutes
    },
  },
  user: {
    additionalFields: {
      defaultOrganization: {
        type: "string",
        required: false,
        input: false,
      },
    },
    changeEmail: {
      enabled: true,
    },
    deleteUser: {
      enabled: true,
    },
  },
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: true,
  },
  socialProviders: {
    microsoft: {
      clientId: env.MICROSOFT_CLIENT_ID,
      clientSecret: env.MICROSOFT_CLIENT_SECRET,
      getUserInfo: async (token) => {
        const res = await fetch("https://graph.microsoft.com/v1.0/me", {
          headers: {
            Authorization: `Bearer ${token.accessToken}`,
          },
        });
        const user = await res.json();
        console.log(user);

        return {
          user: {
            id: user.id,
            name: user.displayName,
            email: user.userPrincipalName,
            emailVerified: true,
            createdAt: new Date(),
            updatedAt: new Date(),
          },
          data: user.data,
        };
      },
    },
  },

  plugins: [openAPI(), passkey(), nextCookies(), organization(), adminPlugin()],
} satisfies BetterAuthOptions;

Additional context

No response

Originally created by @msywulak on GitHub (Jan 4, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/1131 ### Is this suited for github? - [X] Yes, this is suited for github ### To Reproduce Add the organization plugin to your config ```typescript plugins: [openAPI(), passkey(), nextCookies(), organization(), adminPlugin()], ``` add organizationClient to your client ```typescript export const authClient = createAuthClient({ plugins: [ passkeyClient(), magicLinkClient(), organizationClient(), adminClient(), ], }); ``` add to your auth ```typescript import { betterAuth } from "better-auth"; import { authConfig } from "@/lib/auth/config"; import { authActions } from "@/lib/auth/actions"; export const auth = betterAuth({ ...authConfig, ...authActions, }); ``` ### Current vs. Expected behavior Currently the following hooks are Any typed. I would expect them to have the appropriate types for the organization plugin. ![image](https://github.com/user-attachments/assets/e37f94a3-752d-4116-9eee-93c486cca571) ### What version of Better Auth are you using? 1.1.9 ### Provide environment information ```bash - Windows 11 ``` ### Which area(s) are affected? (Select all that apply) Types ### Auth config (if applicable) ```typescript import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { db } from "@/db"; import { openAPI, organization, admin as adminPlugin, } from "better-auth/plugins"; import { passkey } from "better-auth/plugins/passkey"; import { APP_NAME } from "@/utils/constants"; import { env } from "@/env"; import { BetterAuthOptions } from "better-auth"; import { nextCookies } from "better-auth/next-js"; export const authConfig = { appName: APP_NAME, baseURL: env.NODE_ENV === "production" ? env.NEXT_PUBLIC_APP_URL : "http://app.localhost:3000", trustedOrigins: [ env.NEXT_PUBLIC_APP_URL, "http://app.localhost:3000", "http://localhost:3000", ], logger: { disabled: env.NODE_ENV === "production", level: "debug", }, database: drizzleAdapter(db, { provider: "pg", }), session: { freshAge: 0, expiresIn: 60 * 60 * 24 * 3, // 3 days updateAge: 60 * 60 * 12, // 12 hours (every 12 hours the session expiration is updated) cookieCache: { enabled: true, maxAge: 60 * 5, // 5 minutes }, }, user: { additionalFields: { defaultOrganization: { type: "string", required: false, input: false, }, }, changeEmail: { enabled: true, }, deleteUser: { enabled: true, }, }, emailAndPassword: { enabled: true, requireEmailVerification: true, }, socialProviders: { microsoft: { clientId: env.MICROSOFT_CLIENT_ID, clientSecret: env.MICROSOFT_CLIENT_SECRET, getUserInfo: async (token) => { const res = await fetch("https://graph.microsoft.com/v1.0/me", { headers: { Authorization: `Bearer ${token.accessToken}`, }, }); const user = await res.json(); console.log(user); return { user: { id: user.id, name: user.displayName, email: user.userPrincipalName, emailVerified: true, createdAt: new Date(), updatedAt: new Date(), }, data: user.data, }; }, }, }, plugins: [openAPI(), passkey(), nextCookies(), organization(), adminPlugin()], } satisfies BetterAuthOptions; ``` ### Additional context _No response_
GiteaMirror added the lockedbug labels 2026-04-13 03:43:39 -05:00
Author
Owner

@yk-sgr commented on GitHub (Jan 5, 2025):

I'm using 1.1.10 on MacOS and I have the same issue.

auth-client.ts

import { env } from "@/env";
import { createAuthClient } from "better-auth/react";
import { organizationClient, adminClient } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  baseURL: env.NEXT_PUBLIC_BASE_URL,
  plugins: [organizationClient(), adminClient()],
});

export const {
  signIn,
  signOut,
  signUp,
  useSession,
  useListOrganizations,
  useActiveOrganization,
} = authClient;

auth-server.ts

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { organization, admin } from "better-auth/plugins";

import { db } from "@/server/db";
import { env } from "@/env";
import { headers } from "next/headers";
import { redirect } from "next/navigation";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
  }),
  emailAndPassword: {
    enabled: true,
  },
  socialProviders: {
    google: {
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
    },
  },
  plugins: [organization(), admin()],
});

image

<!-- gh-comment-id:2571655959 --> @yk-sgr commented on GitHub (Jan 5, 2025): I'm using `1.1.10` on MacOS and I have the same issue. `auth-client.ts` ```ts import { env } from "@/env"; import { createAuthClient } from "better-auth/react"; import { organizationClient, adminClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ baseURL: env.NEXT_PUBLIC_BASE_URL, plugins: [organizationClient(), adminClient()], }); export const { signIn, signOut, signUp, useSession, useListOrganizations, useActiveOrganization, } = authClient; ``` `auth-server.ts` ```ts import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { organization, admin } from "better-auth/plugins"; import { db } from "@/server/db"; import { env } from "@/env"; import { headers } from "next/headers"; import { redirect } from "next/navigation"; export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", }), emailAndPassword: { enabled: true, }, socialProviders: { google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }, }, plugins: [organization(), admin()], }); ``` ![image](https://github.com/user-attachments/assets/969309ac-f04f-4a96-83d3-bb84db23ac50)
Author
Owner

@ping-maxwell commented on GitHub (Jan 5, 2025):

@msywulak I know this is aside the point, but I do want to point out that you need to put the nextCookies plugin at the end of the plugins array.

<!-- gh-comment-id:2571692060 --> @ping-maxwell commented on GitHub (Jan 5, 2025): @msywulak I know this is aside the point, but I do want to point out that you need to put the `nextCookies` plugin at the end of the plugins array.
Author
Owner

@mamlzy commented on GitHub (Jan 5, 2025):

@Multinite still not getting the type, even already set the nextCookies plugin

auth-client.ts

import { nextCookies } from 'better-auth/next-js';
import { createAuthClient } from 'better-auth/react';

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL!, // the base url of your auth server
  emailAndPassword: {
    enabled: true,
  },
  plugins: [usernameClient(), organizationClient(), nextCookies()],
});

image

<!-- gh-comment-id:2571693489 --> @mamlzy commented on GitHub (Jan 5, 2025): @Multinite still not getting the type, even already set the `nextCookies` plugin `auth-client.ts` ```ts import { organizationClient, usernameClient } from 'better-auth/client/plugins'; import { nextCookies } from 'better-auth/next-js'; import { createAuthClient } from 'better-auth/react'; export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_API_BASE_URL!, // the base url of your auth server emailAndPassword: { enabled: true, }, plugins: [usernameClient(), organizationClient(), nextCookies()], }); ``` ![image](https://github.com/user-attachments/assets/2ac639b9-edb4-4ea7-81e4-4fc2318582ee)
Author
Owner

@ping-maxwell commented on GitHub (Jan 5, 2025):

Yeah, I know. It was just something I wanted to point out, since otherwise it will cause errors.
this is not related to the issue at hand

<!-- gh-comment-id:2571694117 --> @ping-maxwell commented on GitHub (Jan 5, 2025): Yeah, I know. It was just something I wanted to point out, since otherwise it will cause errors. this is not related to the issue at hand
Author
Owner

@Bekacru commented on GitHub (Jan 6, 2025):

@mamlzy remove nextcookies from the clinet plugins list. It's not a client plugin. emailAndPassword enabled shouldn't be passed to the client as well.

<!-- gh-comment-id:2573758188 --> @Bekacru commented on GitHub (Jan 6, 2025): @mamlzy remove nextcookies from the clinet plugins list. It's not a client plugin. `emailAndPassword` enabled shouldn't be passed to the client as well.
Author
Owner

@Bekacru commented on GitHub (Jan 6, 2025):

@yk-sgr and @msywulak check if you have set strict:true on your tsconfig

<!-- gh-comment-id:2573759058 --> @Bekacru commented on GitHub (Jan 6, 2025): @yk-sgr and @msywulak check if you have set `strict:true` on your tsconfig
Author
Owner

@msywulak commented on GitHub (Jan 6, 2025):

@yk-sgr and @msywulak check if you have set strict:true on your tsconfig

Here's my current tsconfig.

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    },
    "target": "ES2017"
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    "lib/middleware",
    "db/schema/auth.ts"
  ],
  "exclude": ["node_modules"]
}
<!-- gh-comment-id:2573778998 --> @msywulak commented on GitHub (Jan 6, 2025): > @yk-sgr and @msywulak check if you have set `strict:true` on your tsconfig Here's my current tsconfig. ```json { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] }, "target": "ES2017" }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "lib/middleware", "db/schema/auth.ts" ], "exclude": ["node_modules"] } ```
Author
Owner

@ping-maxwell commented on GitHub (Jan 6, 2025):

There is a deeper issue to this.
Are you guys able reproduce this in a public repo for us to see?

<!-- gh-comment-id:2573831365 --> @ping-maxwell commented on GitHub (Jan 6, 2025): There is a deeper issue to this. Are you guys able reproduce this in a public repo for us to see?
Author
Owner

@msywulak commented on GitHub (Jan 6, 2025):

There is a deeper issue to this. Are you guys able reproduce this in a public repo for us to see?

https://github.com/msywulak/better-auth-test

image

<!-- gh-comment-id:2573867236 --> @msywulak commented on GitHub (Jan 6, 2025): > There is a deeper issue to this. Are you guys able reproduce this in a public repo for us to see? https://github.com/msywulak/better-auth-test ![image](https://github.com/user-attachments/assets/c364cada-256c-41cb-add8-5a5d731c804a)
Author
Owner

@mamlzy commented on GitHub (Jan 6, 2025):

There is a deeper issue to this. Are you guys able reproduce this in a public repo for us to see?

https://github.com/mamlzy/cms-hono

<!-- gh-comment-id:2574119855 --> @mamlzy commented on GitHub (Jan 6, 2025): > There is a deeper issue to this. Are you guys able reproduce this in a public repo for us to see? https://github.com/mamlzy/cms-hono
Author
Owner

@mamlzy commented on GitHub (Jan 7, 2025):

@yk-sgr and @msywulak check if you have set strict:true on your tsconfig

i did set strict to true

<!-- gh-comment-id:2574223179 --> @mamlzy commented on GitHub (Jan 7, 2025): > @yk-sgr and @msywulak check if you have set `strict:true` on your tsconfig i did set strict to true
Author
Owner

@mamlzy commented on GitHub (Jan 8, 2025):

@msywulak @yk-sgr are you guys use monorepo? becuase i'm facing this issue on turborepo

<!-- gh-comment-id:2576698144 --> @mamlzy commented on GitHub (Jan 8, 2025): @msywulak @yk-sgr are you guys use monorepo? becuase i'm facing this issue on turborepo
Author
Owner

@yk-sgr commented on GitHub (Jan 8, 2025):

Nope, no Turborepo. Btw I'm also using strict:true. It's basically the default T3-Starter. I don't think I configured something diffrent.

<!-- gh-comment-id:2577794702 --> @yk-sgr commented on GitHub (Jan 8, 2025): Nope, no Turborepo. Btw I'm also using `strict:true`. It's basically the default T3-Starter. I don't think I configured something diffrent.
Author
Owner

@salvinoto commented on GitHub (Jan 8, 2025):

I am on turborepo, and I'm getting exactly all of these issues. I'm gonna take a look at the types set in the better auth package.

<!-- gh-comment-id:2577800394 --> @salvinoto commented on GitHub (Jan 8, 2025): I am on turborepo, and I'm getting exactly all of these issues. I'm gonna take a look at the types set in the better auth package.
Author
Owner

@msywulak commented on GitHub (Jan 8, 2025):

My example here is a clean create-next-app setup https://github.com/msywulak/better-auth-test that experiences the issue.

<!-- gh-comment-id:2578395050 --> @msywulak commented on GitHub (Jan 8, 2025): My example here is a clean create-next-app setup https://github.com/msywulak/better-auth-test that experiences the issue.
Author
Owner

@msywulak commented on GitHub (Jan 9, 2025):

@ping-maxwell @Bekacru

No idea why or how this works but if you take the repo https://github.com/msywulak/better-auth-test and just run pnpm add better-auth@1.0.21 then reload to get the tsserver going the types will appear for useListOrganizations. After, upgrade to pnpm add better-auth@latest and the types are working just fine now -- even after multiple IDE restarts.

I was looking through your /demo/nextjs for a point in time when it worked and just chose that release. But starting a fresh project and doing pnpm add better-auth still has any typed organization hooks.

image

<!-- gh-comment-id:2579026135 --> @msywulak commented on GitHub (Jan 9, 2025): @ping-maxwell @Bekacru No idea why or how this works but if you take the repo https://github.com/msywulak/better-auth-test and just run `pnpm add better-auth@1.0.21` then reload to get the tsserver going the types will appear for `useListOrganizations`. After, upgrade to `pnpm add better-auth@latest` and the types are working just fine now -- even after multiple IDE restarts. I was looking through your /demo/nextjs for a point in time when it worked and just chose that release. But starting a fresh project and doing `pnpm add better-auth` still has `any` typed organization hooks. ![image](https://github.com/user-attachments/assets/be425979-a7cb-4cf9-ad3e-60fe516c2a24)
Author
Owner

@msywulak commented on GitHub (Jan 9, 2025):

Still fails in ci though.

[lint] next lint exited with code 0
[format] All matched files use Prettier code style!
[format] pnpm run format:check exited with code 0
Error: [typecheck] components/layout/sidebar/cmdk-org-switcher.tsx(144,41): error TS7006: Parameter 'org' implicitly has an 'any' type.
[typecheck] tsc --noEmit exited with code 2
 ELIFECYCLE  Command failed with exit code 1.
Error: Process completed with exit code 1.
<!-- gh-comment-id:2579108595 --> @msywulak commented on GitHub (Jan 9, 2025): Still fails in ci though. ```bash [lint] next lint exited with code 0 [format] All matched files use Prettier code style! [format] pnpm run format:check exited with code 0 Error: [typecheck] components/layout/sidebar/cmdk-org-switcher.tsx(144,41): error TS7006: Parameter 'org' implicitly has an 'any' type. [typecheck] tsc --noEmit exited with code 2  ELIFECYCLE  Command failed with exit code 1. Error: Process completed with exit code 1. ```
Author
Owner

@mamlzy commented on GitHub (Jan 9, 2025):

Still fails in ci though.

[lint] next lint exited with code 0
[format] All matched files use Prettier code style!
[format] pnpm run format:check exited with code 0
Error: [typecheck] components/layout/sidebar/cmdk-org-switcher.tsx(144,41): error TS7006: Parameter 'org' implicitly has an 'any' type.
[typecheck] tsc --noEmit exited with code 2
 ELIFECYCLE  Command failed with exit code 1.
Error: Process completed with exit code 1.

facing the same thing😕

<!-- gh-comment-id:2579234275 --> @mamlzy commented on GitHub (Jan 9, 2025): > Still fails in ci though. > > ```shell > [lint] next lint exited with code 0 > [format] All matched files use Prettier code style! > [format] pnpm run format:check exited with code 0 > Error: [typecheck] components/layout/sidebar/cmdk-org-switcher.tsx(144,41): error TS7006: Parameter 'org' implicitly has an 'any' type. > [typecheck] tsc --noEmit exited with code 2 >  ELIFECYCLE  Command failed with exit code 1. > Error: Process completed with exit code 1. > ``` facing the same thing😕
Author
Owner

@undefinedhuman commented on GitHub (Jan 13, 2025):

Facing the same issue when using Vue + Vite - but using nx for a monorepo. "strict" is set to true in my tsconfig. If you need more info, please let me know, happy to provide anything you might need.

better-auth: 1.1.11

<!-- gh-comment-id:2588365653 --> @undefinedhuman commented on GitHub (Jan 13, 2025): Facing the same issue when using Vue + Vite - but using nx for a monorepo. "strict" is set to true in my tsconfig. If you need more info, please let me know, happy to provide anything you might need. better-auth: 1.1.11
Author
Owner

@undefinedhuman commented on GitHub (Jan 14, 2025):

Fixed in 1.1.12 (in my case)

<!-- gh-comment-id:2590933467 --> @undefinedhuman commented on GitHub (Jan 14, 2025): Fixed in 1.1.12 (in my case)
Author
Owner

@mamlzy commented on GitHub (Jan 14, 2025):

Fixed in 1.1.12 (in my case)

are you on react? the fix commit is for vue tho🤔

<!-- gh-comment-id:2591221459 --> @mamlzy commented on GitHub (Jan 14, 2025): > Fixed in 1.1.12 (in my case) are you on react? the fix commit is for vue tho🤔
Author
Owner

@undefinedhuman commented on GitHub (Jan 14, 2025):

I am on Vue

<!-- gh-comment-id:2591267640 --> @undefinedhuman commented on GitHub (Jan 14, 2025): I am on Vue
Author
Owner

@mamlzy commented on GitHub (Jan 15, 2025):

I can tell this issue is fixed on the latest version, mine on version 1.1.13.

image

but only works in prod, in dev i got this error while sign-in w/ username

ERROR [Better Auth]: TypeError TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
<!-- gh-comment-id:2591606783 --> @mamlzy commented on GitHub (Jan 15, 2025): I can tell this issue is fixed on the latest version, mine on version `1.1.13`. ![image](https://github.com/user-attachments/assets/5ea4cc07-d3f5-4d1d-9c0c-3754cd69e60f) but only works in prod, in dev i got this error while sign-in w/ username ```ts ERROR [Better Auth]: TypeError TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined ```
Author
Owner

@mamlzy commented on GitHub (Jan 15, 2025):

how about you @msywulak?

<!-- gh-comment-id:2591612606 --> @mamlzy commented on GitHub (Jan 15, 2025): how about you @msywulak?
Author
Owner

@msywulak commented on GitHub (Jan 18, 2025):

Seems like I'm all good in "better-auth": "1.1.14" and works in brand new projects too.

<!-- gh-comment-id:2599505004 --> @msywulak commented on GitHub (Jan 18, 2025): Seems like I'm all good in `"better-auth": "1.1.14"` and works in brand new projects too.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#8609