Skip to content

Commit bf3b2a9

Browse files
committed
perf(router): trust fused request enhancement
1 parent 8e7809a commit bf3b2a9

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

storage/framework/core/router/src/stacks-router.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1601,7 +1601,11 @@ function createMiddlewareHandler(routeKey: string, handler: StacksHandler): Rout
16011601
)
16021602
}
16031603
}
1604-
const enhancedReq = enhanceRequest(req)
1604+
// bun-router dispatches only after its enhancer has installed both its
1605+
// macros and the Stacks prototype. The fused enhancer also initializes the
1606+
// request id, so running the public fallback decorator again here only
1607+
// repeats params assignment and a marker lookup.
1608+
const enhancedReq = req
16051609
const csrfHandledByOuter = (enhancedReq as unknown as Record<symbol, unknown>)[CSRF_SEEDED_BY_HANDLE_REQUEST] === true
16061610

16071611
// Mint the CSRF token BEFORE the handler runs, not after.
@@ -3477,6 +3481,8 @@ function fuseRequestEnhancements(router: Router): void {
34773481
enhanced.params = params
34783482
}
34793483
Object.setPrototypeOf(enhanced, combined)
3484+
if (!enhanced._requestId)
3485+
enhanced._requestId = incomingRequestId(enhanced) ?? crypto.randomUUID()
34803486
return enhanced
34813487
}
34823488

storage/framework/core/router/tests/hot-path.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,19 @@ describe('the request path keeps its defaults', () => {
6565
expect(answer.headers.get('set-cookie') ?? '').toContain('X-CSRF-Token=')
6666
})
6767

68+
it('initializes request ids on warm direct dispatches', async () => {
69+
const { createStacksRouter } = await import('../src')
70+
const direct = createStacksRouter()
71+
direct.get('/_hot/direct-id', () => ({ ok: true }))
72+
73+
const first = await direct.bunRouter.handleRequest(new Request('http://localhost/_hot/direct-id'))
74+
const second = await direct.bunRouter.handleRequest(new Request('http://localhost/_hot/direct-id'))
75+
76+
expect(first.headers.get('x-request-id')).toBeTruthy()
77+
expect(second.headers.get('x-request-id')).toBeTruthy()
78+
expect(second.headers.get('x-request-id')).not.toBe(first.headers.get('x-request-id'))
79+
})
80+
6881
it('still seeds a CSRF cookie on a cold GET', async () => {
6982
const answer = await get('/_hot/plain')
7083

0 commit comments

Comments
 (0)