fix: await ctx in middleware (#3783)

* fix: await ctx in middleware

* fix: lint

* Create tidy-impalas-fail.md
This commit is contained in:
Alex Yang
2025-08-04 10:27:55 -07:00
committed by GitHub
parent 987be984b4
commit d313d0093e
3 changed files with 61 additions and 1 deletions

View File

@@ -0,0 +1,5 @@
---
"better-auth": patch
---
fix: await `ctx` in middleware

View File

@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from "vitest";
import { getEndpoints } from "./index";
import type { AuthContext } from "../init";
import type { BetterAuthOptions, BetterAuthPlugin } from "../types";
import { createAuthMiddleware } from "./call";
describe("getEndpoints", () => {
it("should await promise-based context before passing to middleware", async () => {
const mockContext: AuthContext = {
baseURL: "http://localhost:3000",
options: {},
} as any;
const middlewareFn = vi.fn().mockResolvedValue({});
const testPlugin: BetterAuthPlugin = {
id: "test-plugin",
middlewares: [
{
path: "/test",
middleware: createAuthMiddleware(async (ctx) => {
middlewareFn(ctx);
return {};
}),
},
],
};
const options: BetterAuthOptions = {
plugins: [testPlugin],
};
const promiseContext = new Promise<AuthContext>((resolve) => {
setTimeout(() => resolve(mockContext), 10);
});
const { middlewares } = getEndpoints(promiseContext, options);
const testCtx = {
request: new Request("http://localhost:3000/test"),
context: { customProp: "value" },
};
await middlewares[0].middleware(testCtx);
expect(middlewareFn).toHaveBeenCalled();
const call = middlewareFn.mock.calls[0][0];
expect(call.context).toMatchObject({
baseURL: "http://localhost:3000",
options: {},
customProp: "value",
});
});
});

View File

@@ -72,10 +72,11 @@ export function getEndpoints<
?.map((plugin) =>
plugin.middlewares?.map((m) => {
const middleware = (async (context: any) => {
const authContext = await ctx;
return m.middleware({
...context,
context: {
...ctx,
...authContext,
...context.context,
},
});