Skip to content

Support Bun runtime in Next.js middleware by using passed request instead of headers() #1144

@shandheap

Description

@shandheap

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

  1. Accept an optional request parameter in createCookieHelper(request?)
  2. When a request is provided, extract cookies from request.headers.get('cookie') and use request.headers directly
  3. 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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions