-
Notifications
You must be signed in to change notification settings - Fork 501
Description
Description
When using bun --bun run dev with Next.js 16+, calling stackServerApp.getUser() in middleware fails with:
Error: `headers` was called outside a request scope.
This happens even when explicitly passing the request via tokenStore:
const user = await stackServerApp.getUser({ tokenStore: request }) Root Cause
In packages/template/src/lib/cookie.ts, the createCookieHelper() function unconditionally calls rscHeaders() and rscCookies():
export async function createCookieHelper(): Promise<CookieHelper> {
if (isBrowserLike()) {
return createBrowserCookieHelper();
} else {
return createNextCookieHelper(
await rscCookies(),
await rscHeaders(), // <-- Always called, even when request is available
);
}
} Bun's AsyncLocalStorage implementation doesn't properly propagate Next.js request context, causing headers() to fail in middleware.
Expected Behavior
When tokenStore is a request-like object, the library should use request.headersinstead of calling headers().
Suggested Fix
- Accept an optional request parameter in
createCookieHelper(request?) - When a request is provided, extract cookies from
request.headers.get('cookie')and userequest.headersdirectly - Fall back to
rscHeaders()/rscCookies()when no request is passed (preserving current behavior)
Is it possible to path the stack-auth library so that it no longer requires Next.js promise hooks? The bun runtime provides 20-60% faster response and compilation times so we would appreciate the capability to run our dev flow on bun.
References
Bun Node.js compatability: https://bun.com/docs/runtime/nodejs-compat