[GH-ISSUE #5872] Express js have serverless crash on vercel #27689

Closed
opened 2026-04-17 18:51:23 -05:00 by GiteaMirror · 9 comments
Owner

Originally created by @Axyl1410 on GitHub (Nov 9, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5872

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Recently, I integrated Better Auth into my ExpressJS project, and it still works fine on my machine and builds successfully on Vercel. However, after I accessed it, there was a bug; it broke.

Current vs. Expected behavior

I tried tracing each piece of code and realized the error was here.

// this line make crash
    app.all("/api/auth/*splat", toNodeHandler(auth));
	
	app
	.use(cors(corsOptions))
	.use(express.json())
	.use(express.urlencoded({ extended: true }))
	.use(logMiddleware);

// i cant use because above code
	app.get(
		"/docs",
		apiReference({
			pageTitle: "API Documentation",
			sources: [
				// Better Auth schema generation endpoint
				{ url: "/api/auth/open-api/generate-schema", title: "Auth" },
			],
		})
	);

What version of Better Auth are you using?

^1.3.34

System info

{
  "system": {
    "platform": "win32",
    "arch": "x64",
    "version": "Windows 11 Home",
    "release": "10.0.26100",
    "cpuCount": 20,
    "cpuModel": "13th Gen Intel(R) Core(TM) i7-13650HX",
    "totalMemory": "23.73 GB",
    "freeMemory": "5.81 GB"
  },
  "node": {
    "version": "v22.15.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "11.6.0"
  },
  "frameworks": [
    {
      "name": "express",
      "version": "^5.1.0"
    }
  ],
  "databases": [
    {
      "name": "@prisma/client",
      "version": "^6.16.1"
    }
  ],
  "betterAuth": {
    "version": "^1.3.34",
    "config": {
      "emailAndPassword": {
        "enabled": true,
        "autoSignIn": false,
        "requireEmailVerification": true,
        "resetPasswordTokenExpiresIn": 3600,
        "minPasswordLength": 6
      },
      "emailVerification": {
        "sendOnSignUp": true,
        "expiresIn": 3600,
        "autoSignInAfterVerification": true
      },
      "socialProviders": {
        "github": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]"
        },
        "discord": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]"
        },
        "google": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]"
        }
      },
      "account": {
        "accountLinking": {
          "enabled": true,
          "trustedProviders": [
            "google",
            "github",
            "discord"
          ]
        }
      },
      "rateLimit": {
        "enabled": true
      },
      "plugins": [
        {
          "name": "admin",
          "config": {
            "id": "admin",
            "hooks": {
              "after": [
                {}
              ]
            },
            "endpoints": {},
            "$ERROR_CODES": {
              "FAILED_TO_CREATE_USER": "Failed to create user",
              "USER_ALREADY_EXISTS": "User already exists.",
              "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "User already exists. Use another email.",
              "YOU_CANNOT_BAN_YOURSELF": "You cannot ban yourself",
              "YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE": "You are not allowed to change users role",
              "YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS": "You are not allowed to create users",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS": "You are not allowed to list users",
              "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS": "You are not allowed to list users sessions",
              "YOU_ARE_NOT_ALLOWED_TO_BAN_USERS": "You are not allowed to ban users",
              "YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS": "You are not allowed to impersonate users",
              "YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS": "You are not allowed to revoke users sessions",
              "YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS": "You are not allowed to delete users",
              "YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD": "[REDACTED]",
              "BANNED_USER": "You have been banned from this application",
              "YOU_ARE_NOT_ALLOWED_TO_GET_USER": "You are not allowed to get user",
              "NO_DATA_TO_UPDATE": "No data to update",
              "YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS": "You are not allowed to update users",
              "YOU_CANNOT_REMOVE_YOURSELF": "You cannot remove yourself",
              "YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE": "You are not allowed to set a non-existent role value"
            },
            "schema": {
              "user": {
                "fields": {
                  "role": {
                    "type": "string",
                    "required": false,
                    "input": false
                  },
                  "banned": {
                    "type": "boolean",
                    "defaultValue": false,
                    "required": false,
                    "input": false
                  },
                  "banReason": {
                    "type": "string",
                    "required": false,
                    "input": false
                  },
                  "banExpires": {
                    "type": "date",
                    "required": false,
                    "input": false
                  }
                }
              },
              "session": {
                "fields": {
                  "impersonatedBy": {
                    "type": "string",
                    "required": false
                  }
                }
              }
            },
            "options": {
              "adminUserIds": [
                ""
              ]
            }
          }
        },
        {
          "name": "open-api",
          "config": {
            "id": "open-api",
            "endpoints": {}
          }
        }
      ]
    }
  }
}

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

Other

Auth config (if applicable)

import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { admin, openAPI } from "better-auth/plugins";
import {
	sendResetPasswordEmail,
	sendVerificationEmail,
} from "@/services/email.service";
import prisma from "./prisma";
import { assertValue } from "./utils";

export const auth = betterAuth({
	emailAndPassword: {
		enabled: true,
		autoSignIn: false,
		requireEmailVerification: true,
		resetPasswordTokenExpiresIn: 60 * 60,
		minPasswordLength: 6,

		sendResetPassword: async ({ user, url }) => {
			await sendResetPasswordEmail({ name: user.name, email: user.email }, url);
		},
	},
	emailVerification: {
		sendOnSignUp: true,
		expiresIn: 60 * 60,
		autoSignInAfterVerification: true,
		sendVerificationEmail: async ({ user, url }) => {
			await sendVerificationEmail({ name: user.name, email: user.email }, url);
		},
	},
	socialProviders: {
		github: {
			clientId: assertValue(
				process.env.GITHUB_CLIENT_ID,
				"Missing GITHUB_CLIENT_ID"
			),
			clientSecret: assertValue(
				process.env.GITHUB_CLIENT_SECRET,
				"Missing GITHUB_CLIENT_SECRET"
			),
		},
		discord: {
			clientId: assertValue(
				process.env.DISCORD_CLIENT_ID,
				"Missing DISCORD_CLIENT_ID"
			),
			clientSecret: assertValue(
				process.env.DISCORD_CLIENT_SECRET,
				"Missing DISCORD_CLIENT_SECRET"
			),
		},
		google: {
			clientId: assertValue(
				process.env.GOOGLE_CLIENT_ID,
				"Missing GOOGLE_CLIENT_ID"
			),
			clientSecret: assertValue(
				process.env.GOOGLE_CLIENT_SECRET,
				"Missing GOOGLE_CLIENT_SECRET"
			),
		},
	},
	account: {
		accountLinking: {
			enabled: true,
			trustedProviders: ["google", "github", "discord"],
		},
	},
	rateLimit: {
		enabled: true,
	},
	database: prismaAdapter(prisma, {
		provider: "postgresql",
	}),
	plugins: [
		admin({
			//todo add admin user ids
			adminUserIds: [""],
		}),
		openAPI(),
	],
});

Additional context

this is my repository link : https://github.com/Axyl1410/express-app

Originally created by @Axyl1410 on GitHub (Nov 9, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5872 ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce Recently, I integrated Better Auth into my ExpressJS project, and it still works fine on my machine and builds successfully on Vercel. However, after I accessed it, there was a bug; it broke. ### Current vs. Expected behavior I tried tracing each piece of code and realized the error was here. ``` // this line make crash app.all("/api/auth/*splat", toNodeHandler(auth)); app .use(cors(corsOptions)) .use(express.json()) .use(express.urlencoded({ extended: true })) .use(logMiddleware); // i cant use because above code app.get( "/docs", apiReference({ pageTitle: "API Documentation", sources: [ // Better Auth schema generation endpoint { url: "/api/auth/open-api/generate-schema", title: "Auth" }, ], }) ); ``` ### What version of Better Auth are you using? ^1.3.34 ### System info ```bash { "system": { "platform": "win32", "arch": "x64", "version": "Windows 11 Home", "release": "10.0.26100", "cpuCount": 20, "cpuModel": "13th Gen Intel(R) Core(TM) i7-13650HX", "totalMemory": "23.73 GB", "freeMemory": "5.81 GB" }, "node": { "version": "v22.15.0", "env": "development" }, "packageManager": { "name": "npm", "version": "11.6.0" }, "frameworks": [ { "name": "express", "version": "^5.1.0" } ], "databases": [ { "name": "@prisma/client", "version": "^6.16.1" } ], "betterAuth": { "version": "^1.3.34", "config": { "emailAndPassword": { "enabled": true, "autoSignIn": false, "requireEmailVerification": true, "resetPasswordTokenExpiresIn": 3600, "minPasswordLength": 6 }, "emailVerification": { "sendOnSignUp": true, "expiresIn": 3600, "autoSignInAfterVerification": true }, "socialProviders": { "github": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]" }, "discord": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]" }, "google": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]" } }, "account": { "accountLinking": { "enabled": true, "trustedProviders": [ "google", "github", "discord" ] } }, "rateLimit": { "enabled": true }, "plugins": [ { "name": "admin", "config": { "id": "admin", "hooks": { "after": [ {} ] }, "endpoints": {}, "$ERROR_CODES": { "FAILED_TO_CREATE_USER": "Failed to create user", "USER_ALREADY_EXISTS": "User already exists.", "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "User already exists. Use another email.", "YOU_CANNOT_BAN_YOURSELF": "You cannot ban yourself", "YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE": "You are not allowed to change users role", "YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS": "You are not allowed to create users", "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS": "You are not allowed to list users", "YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS": "You are not allowed to list users sessions", "YOU_ARE_NOT_ALLOWED_TO_BAN_USERS": "You are not allowed to ban users", "YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS": "You are not allowed to impersonate users", "YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS": "You are not allowed to revoke users sessions", "YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS": "You are not allowed to delete users", "YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD": "[REDACTED]", "BANNED_USER": "You have been banned from this application", "YOU_ARE_NOT_ALLOWED_TO_GET_USER": "You are not allowed to get user", "NO_DATA_TO_UPDATE": "No data to update", "YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS": "You are not allowed to update users", "YOU_CANNOT_REMOVE_YOURSELF": "You cannot remove yourself", "YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE": "You are not allowed to set a non-existent role value" }, "schema": { "user": { "fields": { "role": { "type": "string", "required": false, "input": false }, "banned": { "type": "boolean", "defaultValue": false, "required": false, "input": false }, "banReason": { "type": "string", "required": false, "input": false }, "banExpires": { "type": "date", "required": false, "input": false } } }, "session": { "fields": { "impersonatedBy": { "type": "string", "required": false } } } }, "options": { "adminUserIds": [ "" ] } } }, { "name": "open-api", "config": { "id": "open-api", "endpoints": {} } } ] } } } ``` ### Which area(s) are affected? (Select all that apply) Other ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { admin, openAPI } from "better-auth/plugins"; import { sendResetPasswordEmail, sendVerificationEmail, } from "@/services/email.service"; import prisma from "./prisma"; import { assertValue } from "./utils"; export const auth = betterAuth({ emailAndPassword: { enabled: true, autoSignIn: false, requireEmailVerification: true, resetPasswordTokenExpiresIn: 60 * 60, minPasswordLength: 6, sendResetPassword: async ({ user, url }) => { await sendResetPasswordEmail({ name: user.name, email: user.email }, url); }, }, emailVerification: { sendOnSignUp: true, expiresIn: 60 * 60, autoSignInAfterVerification: true, sendVerificationEmail: async ({ user, url }) => { await sendVerificationEmail({ name: user.name, email: user.email }, url); }, }, socialProviders: { github: { clientId: assertValue( process.env.GITHUB_CLIENT_ID, "Missing GITHUB_CLIENT_ID" ), clientSecret: assertValue( process.env.GITHUB_CLIENT_SECRET, "Missing GITHUB_CLIENT_SECRET" ), }, discord: { clientId: assertValue( process.env.DISCORD_CLIENT_ID, "Missing DISCORD_CLIENT_ID" ), clientSecret: assertValue( process.env.DISCORD_CLIENT_SECRET, "Missing DISCORD_CLIENT_SECRET" ), }, google: { clientId: assertValue( process.env.GOOGLE_CLIENT_ID, "Missing GOOGLE_CLIENT_ID" ), clientSecret: assertValue( process.env.GOOGLE_CLIENT_SECRET, "Missing GOOGLE_CLIENT_SECRET" ), }, }, account: { accountLinking: { enabled: true, trustedProviders: ["google", "github", "discord"], }, }, rateLimit: { enabled: true, }, database: prismaAdapter(prisma, { provider: "postgresql", }), plugins: [ admin({ //todo add admin user ids adminUserIds: [""], }), openAPI(), ], }); ``` ### Additional context this is my repository link : https://github.com/[Axyl1410/express-app](https://github.com/Axyl1410/express-app)
GiteaMirror added the lockedbug labels 2026-04-17 18:51:23 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Nov 9, 2025):

(tag @better-auth-agent if you would like an answer from the Agent)

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3508421862 --> @better-auth-agent[bot] commented on GitHub (Nov 9, 2025): (tag @better-auth-agent if you would like an answer from the Agent) <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@dosubot[bot] commented on GitHub (Nov 9, 2025):

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

This is suited for GitHub, as it's a reproducible crash with a third-party integration.

Your crash on Vercel is likely due to a combination of Express v5 route syntax, middleware order, and serverless quirks. For Express v5, the wildcard route should be:

app.all('/api/auth/{*any}', toNodeHandler(auth));

not *splat or :splat—using the wrong syntax can break routing or cause crashes in serverless environments like Vercel (reference).

Also, make sure you mount the Better Auth handler before express.json() or express.urlencoded(). These body parsers can interfere with Better Auth and cause requests to hang or endpoints to return NOT_FOUND or 405 errors, especially on Vercel (reference).

Double-check that your baseURL in the Better Auth config matches the path where you mount the handler, including any /api prefix. If you use subrouters, Express strips the prefix, which can cause 404s or crashes—mount directly on the app if possible (reference).

If you still see issues, try Express v4 to see if it's a v5-specific problem, as v5 support is still marked experimental in some docs.

If you can share the exact error message from Vercel, that would help narrow it down further.

To reply, just mention @dosu.


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

<!-- gh-comment-id:3508424497 --> @dosubot[bot] commented on GitHub (Nov 9, 2025): <!-- Greeting --> Hi @Axyl1410! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This is suited for GitHub, as it's a reproducible crash with a third-party integration. Your crash on Vercel is likely due to a combination of Express v5 route syntax, middleware order, and serverless quirks. For Express v5, the wildcard route should be: ```js app.all('/api/auth/{*any}', toNodeHandler(auth)); ``` not `*splat` or `:splat`—using the wrong syntax can break routing or cause crashes in serverless environments like Vercel [(reference)](https://github.com/better-auth/better-auth/issues/3295). Also, make sure you mount the Better Auth handler before `express.json()` or `express.urlencoded()`. These body parsers can interfere with Better Auth and cause requests to hang or endpoints to return NOT_FOUND or 405 errors, especially on Vercel [(reference)](https://github.com/better-auth/better-auth/issues/3295). Double-check that your `baseURL` in the Better Auth config matches the path where you mount the handler, including any `/api` prefix. If you use subrouters, Express strips the prefix, which can cause 404s or crashes—mount directly on the app if possible [(reference)](https://github.com/better-auth/better-auth/issues/3887). If you still see issues, try Express v4 to see if it's a v5-specific problem, as v5 support is still marked experimental in some docs. If you can share the exact error message from Vercel, that would help narrow it down further. <!-- 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/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/2f221236-0a0d-453c-a4a6-a64a4dd2343d?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&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/5872)
Author
Owner

@Axyl1410 commented on GitHub (Nov 9, 2025):

@better-auth-agent @dosu i have try app.all("/api/auth/{*any}", toNodeHandler(auth)); but didnt work, in vercel build successfully but Serverless Function has crashed.

<!-- gh-comment-id:3508438762 --> @Axyl1410 commented on GitHub (Nov 9, 2025): @better-auth-agent @dosu i have try `app.all("/api/auth/{*any}", toNodeHandler(auth));` but didnt work, in vercel build successfully but Serverless Function has crashed.
Author
Owner

@better-auth-agent[bot] commented on GitHub (Nov 9, 2025):

It looks like the crash might be related to the specific routing pattern used. Instead of using "/api/auth/{any}", please try using the standard Express wildcard pattern like "/api/auth/" to ensure correct route matching. Also, double-check that your routing and middleware order are correctly set up so that Better Auth’s handler is initialized before any other middleware that might affect it. It’s a good idea to test the deployment locally using Vercel’s CLI (vercel dev) to see if you can replicate the issue in a serverless-like environment and capture detailed logs. If the issue persists, please review your Vercel configuration for any resource limits or setup issues. Tag @better-auth-agent if you would like an answer from the Agent. Could you share if changing the route pattern and checking the middleware order helped resolve the issue?

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3508439089 --> @better-auth-agent[bot] commented on GitHub (Nov 9, 2025): It looks like the crash might be related to the specific routing pattern used. Instead of using "/api/auth/{*any}", please try using the standard Express wildcard pattern like "/api/auth/*" to ensure correct route matching. Also, double-check that your routing and middleware order are correctly set up so that Better Auth’s handler is initialized before any other middleware that might affect it. It’s a good idea to test the deployment locally using Vercel’s CLI (vercel dev) to see if you can replicate the issue in a serverless-like environment and capture detailed logs. If the issue persists, please review your Vercel configuration for any resource limits or setup issues. Tag @better-auth-agent if you would like an answer from the Agent. Could you share if changing the route pattern and checking the middleware order helped resolve the issue? <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@better-auth-agent[bot] commented on GitHub (Nov 9, 2025):

Hi there, thanks for reaching out! It looks like the crash may be related to how the route is defined for serverless environments on Vercel. One thing to try is updating the route pattern to use a more conventional Express path matcher. For example, change your route from:

app.all("/api/auth/*splat", toNodeHandler(auth));

to something like:

app.all("/api/auth/:splat*", toNodeHandler(auth));

This syntax is known to work better in serverless setups where path parameters need to be properly handled [1]. Also, ensure that there aren’t any middleware conflicts—make sure that no other middleware is interfering with the authentication endpoints before or after the toNodeHandler(auth) call.

If this adjustment doesn’t resolve the issue, please double-check your Vercel serverless function logs for more specific error messages. It might also help to confirm that all required environment variables and configurations for Better Auth are correctly set up for your Vercel deployment. There have been similar reports where nuances in serverless routing or resource limits caused unexpected crashes.

Could you share any specific error logs or additional context from Vercel? Tag @better-auth-agent if you would like an answer from the Agent.

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3508439384 --> @better-auth-agent[bot] commented on GitHub (Nov 9, 2025): Hi there, thanks for reaching out! It looks like the crash may be related to how the route is defined for serverless environments on Vercel. One thing to try is updating the route pattern to use a more conventional Express path matcher. For example, change your route from: app.all("/api/auth/*splat", toNodeHandler(auth)); to something like: app.all("/api/auth/:splat*", toNodeHandler(auth)); This syntax is known to work better in serverless setups where path parameters need to be properly handled [[1]](https://www.better-auth.com/docs/reference/options). Also, ensure that there aren’t any middleware conflicts—make sure that no other middleware is interfering with the authentication endpoints before or after the toNodeHandler(auth) call. If this adjustment doesn’t resolve the issue, please double-check your Vercel serverless function logs for more specific error messages. It might also help to confirm that all required environment variables and configurations for Better Auth are correctly set up for your Vercel deployment. There have been similar reports where nuances in serverless routing or resource limits caused unexpected crashes. Could you share any specific error logs or additional context from Vercel? Tag @better-auth-agent if you would like an answer from the Agent. <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@dosubot[bot] commented on GitHub (Nov 9, 2025):

A serverless crash on Vercel with Better Auth and Express v5 is often caused by middleware order or config mismatches. Make sure you mount the Better Auth handler (toNodeHandler(auth)) before any body parsers like express.json() or express.urlencoded()—having these before Better Auth can cause crashes or requests to hang in serverless environments like Vercel (source). Also, double-check that your baseURL in the Better Auth config matches the route where you mount the handler, including any /api prefix (source).

If you’re already doing this and still seeing a crash, please share the exact error message or stack trace from the Vercel dashboard. That will help pinpoint whether it’s a config, middleware, or environment issue.

To reply, just mention @dosu.


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

<!-- gh-comment-id:3508442156 --> @dosubot[bot] commented on GitHub (Nov 9, 2025): <!-- Answer --> A serverless crash on Vercel with Better Auth and Express v5 is often caused by middleware order or config mismatches. Make sure you mount the Better Auth handler (toNodeHandler(auth)) before any body parsers like express.json() or express.urlencoded()—having these before Better Auth can cause crashes or requests to hang in serverless environments like Vercel ([source](https://github.com/better-auth/better-auth/issues/3295)). Also, double-check that your baseURL in the Better Auth config matches the route where you mount the handler, including any /api prefix ([source](https://github.com/better-auth/better-auth/pull/5567)). If you’re already doing this and still seeing a crash, please share the exact error message or stack trace from the Vercel dashboard. That will help pinpoint whether it’s a config, middleware, or environment issue. <!-- 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/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/53a1ffbd-fac8-4b95-978b-da9affdeeafc?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&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/5872)
Author
Owner

@himself65 commented on GitHub (Nov 13, 2025):

could you please show the error log?

<!-- gh-comment-id:3524956936 --> @himself65 commented on GitHub (Nov 13, 2025): could you please show the error log?
Author
Owner

@Axyl1410 commented on GitHub (Nov 13, 2025):

could you please show the error log?

@himself65 no errors seen in the console when i deploy in vercel, all i see is 404 not found page

<!-- gh-comment-id:3525700233 --> @Axyl1410 commented on GitHub (Nov 13, 2025): > could you please show the error log? @himself65 no errors seen in the console when i deploy in vercel, all i see is 404 not found page
Author
Owner

@himself65 commented on GitHub (Nov 13, 2025):

The issue is in your vercel.json. Please double-check from the Vercel document.

<!-- gh-comment-id:3529705116 --> @himself65 commented on GitHub (Nov 13, 2025): The issue is in your `vercel.json`. Please double-check from the Vercel document.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#27689