[GH-ISSUE #2405] Unable to make active a organization sql error #9182

Closed
opened 2026-04-13 04:33:17 -05:00 by GiteaMirror · 2 comments
Owner

Originally created by @Asuniia on GitHub (Apr 23, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/2405

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Create a nextjs app router app (15.3.x)
Install BetterAuth and paste config
Migrate db
Create a basic login with BetterAuth
Call function when logged in

Current vs. Expected behavior

I'm trying to define an active organization for the user, but the SQL query performed by BetterAuth is empty. The SET is empty, and the query fails.

Image Image Image

Error:

db-1           | 2025-04-23 07:51:47.637 UTC [1598] ERROR:  syntax error at or near "where" at character 23
db-1           | 2025-04-23 07:51:47.637 UTC [1598] STATEMENT:  update "session" set  where "session"."token" = $1 returning "id", "expires_at", "token", "created_at", "updated_at", "ip_address", "user_agent", "user_id", "impersonated_by"
portabase-app  |  ⨯ error: syntax error at or near "where"
portabase-app  |     at async setActiveOrganization (src/lib/auth/auth.ts:246:8)
portabase-app  |     at async AppSidebar (src/components/wrappers/dashboard/sideBar/app-sidebar.tsx:34:25)
portabase-app  |   244 |     console.log(
portabase-app  |   245 |         "hhhhhuuuuhhhh",
portabase-app  | > 246 |         await auth.api.setActiveOrganization({
portabase-app  |       |        ^
portabase-app  |   247 |             headers: await headers(),
portabase-app  |   248 |             body: {
portabase-app  |   249 |                 organizationSlug: slug, {
portabase-app  |   length: 94,
portabase-app  |   severity: 'ERROR',
portabase-app  |   code: '42601',
portabase-app  |   detail: undefined,
portabase-app  |   hint: undefined,
portabase-app  |   position: '23',
portabase-app  |   internalPosition: undefined,
portabase-app  |   internalQuery: undefined,
portabase-app  |   where: undefined,
portabase-app  |   schema: undefined,
portabase-app  |   table: undefined,
portabase-app  |   column: undefined,
portabase-app  |   dataType: undefined,
portabase-app  |   constraint: undefined,
portabase-app  |   file: 'scan.l',
portabase-app  |   line: '1244',
portabase-app  |   routine: 'scanner_yyerror',
portabase-app  |   digest: '1818293341'
portabase-app  | }

What version of Better Auth are you using?

1.2.7

Provide environment information

OS: MacOS Sequoia 15.2 Intel
Browser: Brave v1.76.81 Chromium: 134.0.6998.166 (Official Build)

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

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/db";
import { env } from "@/env.mjs";
import { nextCookies } from "better-auth/next-js";
import { admin as adminPlugin, organization } from "better-auth/plugins";
import { ac, admin, user, pending, superadmin, orgOwner, orgAdmin, orgMember } from "@/lib/auth/permissions";

import { headers } from "next/headers";
import { count } from "drizzle-orm";
import * as drizzleUser from "@/db/schema/01_user";
import * as drizzleOrganization from "@/db/schema/02_organization";

export const auth = betterAuth({
    database: drizzleAdapter(db, {
        provider: "pg",
        schema: {
            ...drizzleUser,
            ...drizzleOrganization,
        },
    }),
    emailAndPassword: {
        enabled: true,
        requireEmailVerification: false,
        /*async sendResetPassword(data, request) {
            // Send an email to the user with a link to reset their password
        },
        async sendVerificationEmail(data, request) {
            // Send an email to the user with a link to verify their email
        },
        async verifyEmail(data, request) {
            // Verify the email address
        },*/
    },
    socialProviders: {
        google: {
            clientId: env.AUTH_GOOGLE_ID!,
            clientSecret: env.AUTH_GOOGLE_SECRET!,
        },
    },
    plugins: [
        nextCookies(),
        organization({
            ac,
            roles: {
                orgOwner,
                orgAdmin,
                orgMember,
            },
        }),
        adminPlugin({
            adminRoles: ["admin", "superadmin"],
            defaultRole: (await db.select({ count: count() }).from(drizzleUser["user"]))[0].count === 0 ? "superadmin" : "pending",
            ac,
            roles: {
                admin,
                user,
                pending,
                superadmin,
            },
        }),
    ],
    advanced: {
        database: {
            generateId: false,
        },
    },
    user: {
        additionalFields: {
            deletedAt: {
                type: "number", //pg timestamp
                nullable: true,
            },
        },
    },
    trustedOrigins: [env.NEXT_PUBLIC_PROJECT_URL, "http://app"],
});

/*export const signUpUser = async (email: string, password: string, name: string) => {
    const user = await auth.api.signUpEmail({
        body: {
            email,
            password,
            name,
        },
    });

    return user;
};

export const signInUser = async (email: string, password: string) => {
    const user = await auth.api.signInEmail({
        body: {
            email,
            password,
        },
    });

    return user;
};*/

export const createUser = async (name: string, email: string, password: string, role: "user" | "pending" | "admin" | "superadmin" = "pending") => {
    const user = await auth.api.createUser({
        headers: await headers(),
        body: {
            name,
            email,
            password,
            role,
        },
    });

    return user;
};

/*export const hasPermission = async (user: User, permission: { key: string; value: string[] }) => {
    const hasPermission = await auth.api.userHasPermission({
        body: {
            userId: user!.id,
            permission: { subscriber: ["create"] },
        },
    });
};*/

export const getSessions = async () => {
    const sessions = await auth.api.listSessions({
        headers: await headers(),
    });

    return sessions;
};

export const getSession = async () => {
    const session = await auth.api.getSession({
        headers: await headers(),
    });

    return session;
};

export const revokeSession = async (e: string) => {
    try {
        const { status } = await auth.api.revokeSession({
            body: {
                token: e,
            },
            headers: await headers(),
        });
        return status;
    } catch (e) {}
};

export const getAccounts = async () => {
    const sessions = await auth.api.listUserAccounts({
        headers: await headers(),
    });

    return sessions;
};

export const unlinkAccount = async (provider: string, account: string) => {
    try {
        const { status } = await auth.api.unlinkAccount({
            body: {
                providerId: provider,
                accountId: account,
            },
            headers: await headers(),
        });

        return status;
    } catch (e) {}
};

export const getOrganization = async (organizationSlug?: string) => {
    try {
        const organization = await auth.api.getFullOrganization({
            headers: await headers(),
            query: {
                organizationSlug,
            },
        });

        return organization;
    } catch (e) {}
};

export const listOrganizations = async () => {
    try {
        const organizations = await auth.api.listOrganizations({
            headers: await headers(),
        });

        return organizations;
    } catch (e) {
        console.log("err", e);
    }
};

export const createOrganization = async (name: string, slug: string) => {
    try {
        const organization = await auth.api.createOrganization({
            headers: await headers(),
            body: {
                name,
                slug,
            },
        });

        return organization;
    } catch (e) {
        console.log("err", e);
    }
};

export const checkSlugOrganization = async (slug: string) => {
    try {
        const { status } = await auth.api.checkOrganizationSlug({
            headers: await headers(),
            body: {
                slug,
            },
        });

        return status;
    } catch (e) {
        console.log("err", e);
    }
};

export const getActiveMember = async () => {
    try {
        const member = await auth.api.getActiveMember({
            headers: await headers(),
        });

        return member;
    } catch (e) {
        console.log("err", e);
    }
};

export const setActiveOrganization = async (slug: string) => {
    try {
        const organization = await auth.api.setActiveOrganization({
            headers: await headers(),
            body: {
                organizationSlug: slug,
            },
        });
        return organization;
    } catch (e) {
        console.log("error", e);
    }
};

Additional context

No response

Originally created by @Asuniia on GitHub (Apr 23, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/2405 ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce Create a nextjs app router app (15.3.x) Install BetterAuth and paste config Migrate db Create a basic login with BetterAuth Call function when logged in ### Current vs. Expected behavior I'm trying to define an active organization for the user, but the SQL query performed by BetterAuth is empty. The SET is empty, and the query fails. <img width="557" alt="Image" src="https://github.com/user-attachments/assets/d12064d9-db87-4911-949f-e6a67e50d804" /> <img width="669" alt="Image" src="https://github.com/user-attachments/assets/b4adeb1b-b310-4861-89db-4e9f69629cdb" /> <img width="1157" alt="Image" src="https://github.com/user-attachments/assets/9c895c54-66c4-462e-a268-178c778ad51b" /> Error: ``` db-1 | 2025-04-23 07:51:47.637 UTC [1598] ERROR: syntax error at or near "where" at character 23 db-1 | 2025-04-23 07:51:47.637 UTC [1598] STATEMENT: update "session" set where "session"."token" = $1 returning "id", "expires_at", "token", "created_at", "updated_at", "ip_address", "user_agent", "user_id", "impersonated_by" portabase-app | ⨯ error: syntax error at or near "where" portabase-app | at async setActiveOrganization (src/lib/auth/auth.ts:246:8) portabase-app | at async AppSidebar (src/components/wrappers/dashboard/sideBar/app-sidebar.tsx:34:25) portabase-app | 244 | console.log( portabase-app | 245 | "hhhhhuuuuhhhh", portabase-app | > 246 | await auth.api.setActiveOrganization({ portabase-app | | ^ portabase-app | 247 | headers: await headers(), portabase-app | 248 | body: { portabase-app | 249 | organizationSlug: slug, { portabase-app | length: 94, portabase-app | severity: 'ERROR', portabase-app | code: '42601', portabase-app | detail: undefined, portabase-app | hint: undefined, portabase-app | position: '23', portabase-app | internalPosition: undefined, portabase-app | internalQuery: undefined, portabase-app | where: undefined, portabase-app | schema: undefined, portabase-app | table: undefined, portabase-app | column: undefined, portabase-app | dataType: undefined, portabase-app | constraint: undefined, portabase-app | file: 'scan.l', portabase-app | line: '1244', portabase-app | routine: 'scanner_yyerror', portabase-app | digest: '1818293341' portabase-app | } ``` ### What version of Better Auth are you using? 1.2.7 ### Provide environment information ```bash OS: MacOS Sequoia 15.2 Intel Browser: Brave v1.76.81 Chromium: 134.0.6998.166 (Official Build) ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { db } from "@/db"; import { env } from "@/env.mjs"; import { nextCookies } from "better-auth/next-js"; import { admin as adminPlugin, organization } from "better-auth/plugins"; import { ac, admin, user, pending, superadmin, orgOwner, orgAdmin, orgMember } from "@/lib/auth/permissions"; import { headers } from "next/headers"; import { count } from "drizzle-orm"; import * as drizzleUser from "@/db/schema/01_user"; import * as drizzleOrganization from "@/db/schema/02_organization"; export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", schema: { ...drizzleUser, ...drizzleOrganization, }, }), emailAndPassword: { enabled: true, requireEmailVerification: false, /*async sendResetPassword(data, request) { // Send an email to the user with a link to reset their password }, async sendVerificationEmail(data, request) { // Send an email to the user with a link to verify their email }, async verifyEmail(data, request) { // Verify the email address },*/ }, socialProviders: { google: { clientId: env.AUTH_GOOGLE_ID!, clientSecret: env.AUTH_GOOGLE_SECRET!, }, }, plugins: [ nextCookies(), organization({ ac, roles: { orgOwner, orgAdmin, orgMember, }, }), adminPlugin({ adminRoles: ["admin", "superadmin"], defaultRole: (await db.select({ count: count() }).from(drizzleUser["user"]))[0].count === 0 ? "superadmin" : "pending", ac, roles: { admin, user, pending, superadmin, }, }), ], advanced: { database: { generateId: false, }, }, user: { additionalFields: { deletedAt: { type: "number", //pg timestamp nullable: true, }, }, }, trustedOrigins: [env.NEXT_PUBLIC_PROJECT_URL, "http://app"], }); /*export const signUpUser = async (email: string, password: string, name: string) => { const user = await auth.api.signUpEmail({ body: { email, password, name, }, }); return user; }; export const signInUser = async (email: string, password: string) => { const user = await auth.api.signInEmail({ body: { email, password, }, }); return user; };*/ export const createUser = async (name: string, email: string, password: string, role: "user" | "pending" | "admin" | "superadmin" = "pending") => { const user = await auth.api.createUser({ headers: await headers(), body: { name, email, password, role, }, }); return user; }; /*export const hasPermission = async (user: User, permission: { key: string; value: string[] }) => { const hasPermission = await auth.api.userHasPermission({ body: { userId: user!.id, permission: { subscriber: ["create"] }, }, }); };*/ export const getSessions = async () => { const sessions = await auth.api.listSessions({ headers: await headers(), }); return sessions; }; export const getSession = async () => { const session = await auth.api.getSession({ headers: await headers(), }); return session; }; export const revokeSession = async (e: string) => { try { const { status } = await auth.api.revokeSession({ body: { token: e, }, headers: await headers(), }); return status; } catch (e) {} }; export const getAccounts = async () => { const sessions = await auth.api.listUserAccounts({ headers: await headers(), }); return sessions; }; export const unlinkAccount = async (provider: string, account: string) => { try { const { status } = await auth.api.unlinkAccount({ body: { providerId: provider, accountId: account, }, headers: await headers(), }); return status; } catch (e) {} }; export const getOrganization = async (organizationSlug?: string) => { try { const organization = await auth.api.getFullOrganization({ headers: await headers(), query: { organizationSlug, }, }); return organization; } catch (e) {} }; export const listOrganizations = async () => { try { const organizations = await auth.api.listOrganizations({ headers: await headers(), }); return organizations; } catch (e) { console.log("err", e); } }; export const createOrganization = async (name: string, slug: string) => { try { const organization = await auth.api.createOrganization({ headers: await headers(), body: { name, slug, }, }); return organization; } catch (e) { console.log("err", e); } }; export const checkSlugOrganization = async (slug: string) => { try { const { status } = await auth.api.checkOrganizationSlug({ headers: await headers(), body: { slug, }, }); return status; } catch (e) { console.log("err", e); } }; export const getActiveMember = async () => { try { const member = await auth.api.getActiveMember({ headers: await headers(), }); return member; } catch (e) { console.log("err", e); } }; export const setActiveOrganization = async (slug: string) => { try { const organization = await auth.api.setActiveOrganization({ headers: await headers(), body: { organizationSlug: slug, }, }); return organization; } catch (e) { console.log("error", e); } }; ``` ### Additional context _No response_
GiteaMirror added the lockedbug labels 2026-04-13 04:33:17 -05:00
Author
Owner

@Fesyse commented on GitHub (May 11, 2025):

Experiencing same issue, but instead of setting active organization im creating.

Query: insert into "tasklytic_organization" ("id", "name", "slug", "logo", "created_at", "metadata") values ($1, $2, $3, default, $4, $5) returning "id", "name", "slug", "logo", "created_at", "metadata" -- params: ["IRMPZ2PFXoSbrx977RmUjqo8wA2RzBhy", "tasklytic", "tasklytic", "2025-05-11T10:50:00.375Z", "{\"teamType\":\"solo\",\"layoutType\":\"minimalist\"}"]
Query: insert into "tasklytic_member" ("id", "organization_id", "user_id", "role", "created_at") values ($1, $2, $3, $4, $5) returning "id", "organization_id", "user_id", "role", "created_at" -- params: ["bprZ8VGmFb7pSOoMS9iZULSvLPSaxgKM", "IRMPZ2PFXoSbrx977RmUjqo8wA2RzBhy", "bBTOtmo1h0QyxUyqrNmMA54kCS9BixBe", "owner", "2025-05-11T10:50:00.377Z"]
Query: update "tasklytic_session" set  where "tasklytic_session"."token" = $1 returning "id", "expires_at", "token", "created_at", "updated_at", "ip_address", "user_agent", "user_id" -- params: ["I8bgxs3nsC4ACJmvSkp7iiLuAQgmxbX0"]
# SERVER_ERROR:  [error: syntax error at or near "where"] {
  length: 94,
  severity: 'ERROR',
  code: '42601',
  detail: undefined,
  hint: undefined,
  position: '33',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'scan.l',
  line: '1244',
  routine: 'scanner_yyerror'
}
POST /api/auth/organization/create 500 in 175ms 
<!-- gh-comment-id:2869768456 --> @Fesyse commented on GitHub (May 11, 2025): Experiencing same issue, but instead of setting active organization im creating. ```txt Query: insert into "tasklytic_organization" ("id", "name", "slug", "logo", "created_at", "metadata") values ($1, $2, $3, default, $4, $5) returning "id", "name", "slug", "logo", "created_at", "metadata" -- params: ["IRMPZ2PFXoSbrx977RmUjqo8wA2RzBhy", "tasklytic", "tasklytic", "2025-05-11T10:50:00.375Z", "{\"teamType\":\"solo\",\"layoutType\":\"minimalist\"}"] Query: insert into "tasklytic_member" ("id", "organization_id", "user_id", "role", "created_at") values ($1, $2, $3, $4, $5) returning "id", "organization_id", "user_id", "role", "created_at" -- params: ["bprZ8VGmFb7pSOoMS9iZULSvLPSaxgKM", "IRMPZ2PFXoSbrx977RmUjqo8wA2RzBhy", "bBTOtmo1h0QyxUyqrNmMA54kCS9BixBe", "owner", "2025-05-11T10:50:00.377Z"] Query: update "tasklytic_session" set where "tasklytic_session"."token" = $1 returning "id", "expires_at", "token", "created_at", "updated_at", "ip_address", "user_agent", "user_id" -- params: ["I8bgxs3nsC4ACJmvSkp7iiLuAQgmxbX0"] # SERVER_ERROR: [error: syntax error at or near "where"] { length: 94, severity: 'ERROR', code: '42601', detail: undefined, hint: undefined, position: '33', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'scan.l', line: '1244', routine: 'scanner_yyerror' } POST /api/auth/organization/create 500 in 175ms ```
Author
Owner

@Fesyse commented on GitHub (May 11, 2025):

Solved problem:
Forgot to add activeOrganizationId to session table.
See more: https://www.better-auth.com/docs/plugins/organization#session

<!-- gh-comment-id:2869922426 --> @Fesyse commented on GitHub (May 11, 2025): Solved problem: Forgot to add `activeOrganizationId` to `session` table. See more: <https://www.better-auth.com/docs/plugins/organization#session>
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#9182