SQL error when exchanging the token (Microsoft Auth + MSSQL + NextJS) #1407

Closed
opened 2026-03-13 08:38:28 -05:00 by GiteaMirror · 6 comments
Owner

Originally created by @ludoblues on GitHub (Jun 23, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Create a Microsoft Entry ID app configured following this recommendations
  2. Create a NextJS app
  3. Create an MSSQL database
  4. Configure your auth.ts file to connect your mssql database following this recommendations
  5. Configure the Microsoft social provider
  6. Expose the better-auth/next-js handler route API following this recommendations
  7. Implement a signIn.social call with microsoft as a provider using createAuthClient
  8. Try to sign in with microsoft
  9. You are going to be redirected to Microsoft login
  10. Fill the form with your Microsoft credentials
  11. You are going to be redirected to the microsoft callback url with a code, and the error will happen here on the server side: # SERVER_ERROR: [Error: The data types text and nvarchar are incompatible in the equal to operator.]

Current vs. Expected behavior

I was expecting better-auth to be able to exchange the code with an access_token, but it failed due to an SQL error that seems to be an incompatibility between the better-auth SQL schema and what the better-auth handler is doing behing the scene during the token exchange, trying to perform some invalid operation in MSSQL.

What version of Better Auth are you using?

1.2.9

Provide environment information

- OS: WSL2
- Browser: Google Chrome

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

Backend, Client

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { MssqlDialect } from "kysely";
import * as Tarn from "tarn";
import * as Tedious from "tedious";
 
const dialect = new MssqlDialect({
  tarn: {
    ...Tarn,
    options: {
      min: 1,
      max: 10,
    },
  },
  tedious: {
    ...Tedious,
    connectionFactory: () =>
      new Tedious.Connection({
        server: "localhost",
        authentication: {
          type: "default",
          options: {
            userName: "sa",
            password: "StrongP@ssw0rd!",
          },
        },
        options: {
          database: "betterauth_db",
          port: 1433,
          trustServerCertificate: true,
        },
      }),
  },
});
 
export const auth = betterAuth({
  database: {
    dialect,
    type: "mssql",
  },
  emailAndPassword: {
    enabled: true,
  },
  socialProviders: {
    microsoft: {
      clientId: "*******",
      clientSecret: "*******",
      tenantId: "*******",
      prompt: "select_account"
    },
  },
});

Additional context

No response

Originally created by @ludoblues on GitHub (Jun 23, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Create a Microsoft Entry ID app [configured following this recommendations](https://www.better-auth.com/docs/authentication/microsoft) 2. Create a NextJS app 3. Create an MSSQL database 4. Configure your auth.ts file to connect your mssql database [following this recommendations](https://www.better-auth.com/docs/adapters/mssql) 6. Configure the Microsoft social provider 7. Expose the `better-auth/next-js` handler route API [following this recommendations](https://www.better-auth.com/docs/integrations/next) 8. Implement a `signIn.social` call with `microsoft `as a provider using `createAuthClient` 9. Try to sign in with microsoft 10. You are going to be redirected to Microsoft login 11. Fill the form with your Microsoft credentials 12. You are going to be redirected to the microsoft callback url with a code, and the error will happen here on the server side: `# SERVER_ERROR: [Error: The data types text and nvarchar are incompatible in the equal to operator.] ` ### Current vs. Expected behavior I was expecting better-auth to be able to exchange the code with an access_token, but it failed due to an SQL error that seems to be an incompatibility between the better-auth SQL schema and what the better-auth handler is doing behing the scene during the token exchange, trying to perform some invalid operation in MSSQL. ### What version of Better Auth are you using? 1.2.9 ### Provide environment information ```bash - OS: WSL2 - Browser: Google Chrome ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { MssqlDialect } from "kysely"; import * as Tarn from "tarn"; import * as Tedious from "tedious"; const dialect = new MssqlDialect({ tarn: { ...Tarn, options: { min: 1, max: 10, }, }, tedious: { ...Tedious, connectionFactory: () => new Tedious.Connection({ server: "localhost", authentication: { type: "default", options: { userName: "sa", password: "StrongP@ssw0rd!", }, }, options: { database: "betterauth_db", port: 1433, trustServerCertificate: true, }, }), }, }); export const auth = betterAuth({ database: { dialect, type: "mssql", }, emailAndPassword: { enabled: true, }, socialProviders: { microsoft: { clientId: "*******", clientSecret: "*******", tenantId: "*******", prompt: "select_account" }, }, }); ``` ### Additional context _No response_
GiteaMirror added the social-providernextjs labels 2026-03-13 08:38:29 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Jun 23, 2025):

Hi @ludoblues! I'm Dosu and I’m helping the better-auth team.

The error happens because in MSSQL, Better Auth's default schema maps string fields like providerId and accountId in the account table to the text type, but queries compare them to nvarchar values, which MSSQL doesn't allow without explicit conversion. This is a schema generation issue: unless these fields are marked as unique or sortable, they default to text instead of varchar, causing the incompatibility during authentication flows see code reference.

Workaround:
Update your Better Auth config to mark providerId and accountId as unique or sortable in the schema override for the account table. This will generate them as varchar in MSSQL, which is compatible with nvarchar. After updating, run the migration to update your database schema.

Example:

export const auth = betterAuth({
  // ...other config
  account: {
    fields: {
      providerId: { unique: true },
      accountId: { unique: true },
    },
  },
});

Then re-run your migrations to update the column types in your MSSQL database.

There are currently no tickets or docs mentioning this specific issue, but this approach aligns with how Better Auth's schema logic works for MSSQL see details. This should resolve the error.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Join Discord Share on X

@dosubot[bot] commented on GitHub (Jun 23, 2025): <!-- Greeting --> Hi @ludoblues! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> The error happens because in MSSQL, Better Auth's default schema maps string fields like `providerId` and `accountId` in the `account` table to the `text` type, but queries compare them to `nvarchar` values, which MSSQL doesn't allow without explicit conversion. This is a schema generation issue: unless these fields are marked as `unique` or `sortable`, they default to `text` instead of `varchar`, causing the incompatibility during authentication flows [see code reference](https://github.com/better-auth/better-auth/blob/1eff55bde85427d6bb2fafdc8691c4af11fbc301/packages/better-auth/src/db/get-migration.ts). **Workaround:** Update your Better Auth config to mark `providerId` and `accountId` as `unique` or `sortable` in the schema override for the `account` table. This will generate them as `varchar` in MSSQL, which is compatible with `nvarchar`. After updating, run the migration to update your database schema. Example: ```ts export const auth = betterAuth({ // ...other config account: { fields: { providerId: { unique: true }, accountId: { unique: true }, }, }, }); ``` Then re-run your migrations to update the column types in your MSSQL database. There are currently no tickets or docs mentioning this specific issue, but this approach aligns with how Better Auth's schema logic works for MSSQL [see details](https://github.com/better-auth/better-auth/blob/1eff55bde85427d6bb2fafdc8691c4af11fbc301/packages/better-auth/src/db/get-tables.ts). This should resolve the error. <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/c7d92625-fa9e-443b-841b-e2078c23056d?feedback_type=other)</sup>&nbsp;&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/3143)
Author
Owner

@ludoblues commented on GitHub (Jun 23, 2025):

Hi @dosu,

You understood the issue correctly, but your fix doesn't work, your fields object doesn't match its typescript definition (providerId and accountId should be strings and not objects), and even when trying to give directly unique or sortable or even varchar as a value doesn't fix the table/issue (after a CLI migrate rerun of course).

@ludoblues commented on GitHub (Jun 23, 2025): Hi @dosu, You understood the issue correctly, but your fix doesn't work, your `fields` object doesn't match its typescript definition (`providerId` and `accountId` should be `strings `and not `objects`), and even when trying to give directly `unique `or `sortable `or even `varchar `as a value doesn't fix the table/issue (after a CLI migrate rerun of course).
Author
Owner

@dosubot[bot] commented on GitHub (Jun 23, 2025):

You're right—the config API only lets you remap field names, not change column types or attributes for built-in fields like providerId/accountId. There’s currently no supported way to override these to varchar via config or migration CLI, which is why your attempts had no effect (source, source). The schema logic that would allow this is internal and not exposed to user config.

The only workaround right now is to manually ALTER TABLE after running the migration, changing those columns to varchar (e.g., ALTER TABLE account ALTER COLUMN providerId VARCHAR(255) NOT NULL). Be aware this could break if you re-run migrations or upgrade Better Auth, so keep an eye on future releases for a proper fix or schema override support.

Let me know if you want a sample SQL statement or more details on the manual workaround.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Join Discord Share on X

@dosubot[bot] commented on GitHub (Jun 23, 2025): <!-- Answer --> You're right—the config API only lets you remap field names, not change column types or attributes for built-in fields like providerId/accountId. There’s currently no supported way to override these to varchar via config or migration CLI, which is why your attempts had no effect ([source](https://github.com/better-auth/better-auth/blob/1eff55bde85427d6bb2fafdc8691c4af11fbc301/packages/better-auth/src/types/options.ts), [source](https://github.com/better-auth/better-auth/blob/1eff55bde85427d6bb2fafdc8691c4af11fbc301/packages/better-auth/src/db/get-tables.ts)). The schema logic that would allow this is internal and not exposed to user config. The only workaround right now is to manually ALTER TABLE after running the migration, changing those columns to varchar (e.g., `ALTER TABLE account ALTER COLUMN providerId VARCHAR(255) NOT NULL`). Be aware this could break if you re-run migrations or upgrade Better Auth, so keep an eye on future releases for a proper fix or schema override support. Let me know if you want a sample SQL statement or more details on the manual workaround. <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/f0caae73-2245-43ea-aa51-9aa7cbe5b7fe?feedback_type=other)</sup>&nbsp;&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/3143)
Author
Owner

@ludoblues commented on GitHub (Jun 24, 2025):

I finally could got it working!
My PR fixes the issue for MSSQL

@ludoblues commented on GitHub (Jun 24, 2025): I finally could got it working! My PR fixes the issue for MSSQL
Author
Owner

@AugustasPaliulis commented on GitHub (Jul 31, 2025):

@ludoblues Hey, I saw that you have created PR for fixing this problem. As I understand it is not merged yet? Unless I am mistaken. Are you planning to merge it? Or maybe the whole process is totally different.

@AugustasPaliulis commented on GitHub (Jul 31, 2025): @ludoblues Hey, I saw that you have created PR for fixing this problem. As I understand it is not merged yet? Unless I am mistaken. Are you planning to merge it? Or maybe the whole process is totally different.
Author
Owner

@ludoblues commented on GitHub (Jul 31, 2025):

@AugustasPaliulis as a simple contributor I am not allowed to merge it myself

@ludoblues commented on GitHub (Jul 31, 2025): @AugustasPaliulis as a simple contributor I am not allowed to merge it myself
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1407