fix(auth): use BASE_URL for redirects and handle __Secure- cookie prefix#418
fix(auth): use BASE_URL for redirects and handle __Secure- cookie prefix#418
Conversation
There was a problem hiding this comment.
Pull request overview
This PR fixes production auth redirect behavior by ensuring redirects are built from the externally reachable BASE_URL (aka BETTER_AUTH_URL) and by correctly detecting Better Auth cookies that are __Secure- prefixed under HTTPS, preventing infinite refresh redirect loops.
Changes:
- Update
isTokenNearExpiry()to normalize cookie names by stripping the__Secure-prefix when locating/chunkingbetter-auth.account_data. - Update the token refresh route handler to resolve and validate redirect targets against
BASE_URLrather thanrequest.url. - Add/extend unit tests covering
__Secure-cookies and redirect/base-url behavior in the token refresh route.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| src/lib/auth/utils.ts | Normalizes cookie names to support __Secure- prefixed Better Auth cookies and chunked cookie reads. |
| src/lib/auth/tests/utils.test.ts | Adds tests ensuring __Secure- cookies (including chunked) are read/concatenated correctly. |
| src/app/api/auth/token-refresh/route.ts | Builds redirect validation and redirect responses from BASE_URL to avoid internal bind-address redirects. |
| src/app/api/auth/token-refresh/route.test.ts | Adds route handler unit tests for BASE_URL-based redirects, open-redirect protection, and Set-Cookie forwarding. |
|
@claude succinct review |
|
Claude finished @peppescg's task in 54s —— View job Code ReviewOverall: Solid fix for two real production bugs. Code is clean, well-documented, and well-tested. A couple of minor issues worth addressing.
|
samuv
left a comment
There was a problem hiding this comment.
I don't have much context, but looks good
Summary
Kapture.2026-03-11.at.15.49.48.mp4
route.ts: replacerequest.urlwithBASE_URL(BETTER_AUTH_URL) as the base for allredirects in the Route Handler. In production with
output: standaloneandHOSTNAME=0.0.0.0,request.urlwas built from the internal bind address (0.0.0.0:3000) instead of the externalURL, producing unreachable redirects.
utils.ts:isTokenNearExpiry()never found the cookie in production HTTPS because BetterAuth prefixes cookies with
__Secure-on secure connections. The function was matching againstbetter-auth.account_datawhile the actual cookie was named__Secure-better-auth.account_data, so it always returnedtrue→ infinite redirect loop.The second bug was masked by the first: before the routing fix, the redirect to
0.0.0.0:3000failed immediately with a connection error. Once redirects pointed to the correct origin, the
loop became visible as
ERR_TOO_MANY_REDIRECTS.