Fix social login localhost fallback via relative API routing and resolve OAuth redirect loops (vertex app)#3604
Conversation
Introduce src/vertex/lib/api-routing.ts with buildServerApiUrl and buildBrowserApiUrl to centralize how server- and browser-side API URLs are built (avoids split-brain env issues). Replace scattered getApiBaseUrl usage across auth options, oauth session, users API, network service, and proxy client to use the new builders. Tighten env constants: getApiBaseUrl now requires NEXT_PUBLIC_API_URL (throws if missing) and getEnvironment was moved/renamed. Update vertex.config to use getApiBaseUrl. Misc: adjust variable names in proxy client (API_URL) and ensure browser requests use relative /api/v2 paths.
Switch OAuth initiation to use buildServerApiUrl instead of buildBrowserApiUrl to construct the /users/auth/:provider endpoint. Also adjust proxy path handling to strip a leading "v2/" (and treat "v2" as empty) so requests don't end up with a double /v2/ segment when getApiBaseUrl() already includes it.
Improve OAuth handling across auth flow: - options.ts: increase profile fetch timeout to 10s, normalize the OAuth access token and only send Authorization when present, include credentials in the fetch, and return null on AbortError to avoid logging noise. - social-auth-section.tsx: append a success=<provider> query param to redirect_after URLs so callers can detect successful social sign-ins. - authProvider.tsx: force NextAuth SessionProvider to update after token handoff (await update()), watch session status to clear the isHandlingOAuth flag when authenticated, ensure the flag is cleared on error branches, and adjust bootstrap blocking logic to wait for NextAuth to flush its authenticated state before unblocking. These changes make token handoff more robust and ensure redirects and session state are synchronized correctly.
|
Warning Review limit reached
More reviews will be available in 40 minutes and 49 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughCentralizes API URL building (server/browser), requires NEXT_PUBLIC_API_URL, migrates callsites to the new builders, and tightens OAuth token handoff/session sync and redirect URL construction. ChangesAPI Routing and OAuth Authentication Flow
Sequence DiagramssequenceDiagram
participant Handler as TokenHandoffHandler
participant NextAuth as useSession()
participant SignIn as signIn()
participant Redirect as Navigation
Handler->>NextAuth: Read update & status
Handler->>SignIn: Initiate OAuth sign-in
SignIn-->>Handler: Result OK/Error
alt Sign-in Success
Handler->>NextAuth: Call update() for sync
NextAuth-->>Handler: Session updated
Handler->>NextAuth: Wait for status=authenticated
NextAuth-->>Handler: status changes
Handler->>Redirect: Navigate to destination
else Sign-in Failure
Handler->>Handler: Clear isHandlingOAuthRef
Handler->>Redirect: Navigate to /auth-error
end
flowchart LR
routes[Endpoint paths] --> buildServer[buildServerApiUrl]
routes --> buildBrowser[buildBrowserApiUrl]
buildServer --> users[users.ts]
buildServer --> network[network-service.ts]
buildServer --> proxy[proxyClient.ts]
buildBrowser --> network
users --> api[API calls]
network --> api
proxy --> api
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
New azure vertex changes available for preview here |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/vertex/components/features/auth/social-auth-section.tsx`:
- Around line 93-95: The code constructs a new URL from redirectAfter which will
throw for relative paths; update the logic around the URL(...) creation in
social-auth-section.tsx (where redirectAfter is used and
queryParams.redirect_after is set) to pass a base (e.g., window.location.origin)
to the URL constructor so relative paths like '/home' resolve correctly while
absolute URLs remain unchanged; ensure you still call
urlObj.searchParams.set('success', provider) and assign
queryParams.redirect_after = urlObj.toString().
In `@src/vertex/core/services/network-service.ts`:
- Around line 94-95: submitNetworkRequest currently constructs its POST target
with buildBrowserApiUrl which yields a browser-relative path; when invoked from
server route handlers (submitNetworkRequest in network-service.ts called by
app/api/.../route.ts) this breaks because fetch on the server needs an
absolute/server API URL. Replace buildBrowserApiUrl(...) with
buildServerApiUrl(...) inside submitNetworkRequest (or otherwise construct a
server-resolvable absolute URL) so the server-side call uses the correct API
host/resolver; update any related error handling or tests that assume the old
URL shape.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ce50a1ac-2bd4-4a80-a2ef-ed79f67bab19
📒 Files selected for processing (11)
src/vertex/app/api/auth/[...nextauth]/options.tssrc/vertex/app/changelog.mdsrc/vertex/components/features/auth/social-auth-section.tsxsrc/vertex/core/apis/users.tssrc/vertex/core/auth/authProvider.tsxsrc/vertex/core/auth/oauth-session.tssrc/vertex/core/services/network-service.tssrc/vertex/core/utils/proxyClient.tssrc/vertex/lib/api-routing.tssrc/vertex/lib/envConstants.tssrc/vertex/vertex.config.ts
Return null from SocialAuthSection when NEXT_PUBLIC_API_URL is not set. This avoids runtime crashes during OAuth initiation when getApiBaseUrl() would throw due to a missing API URL environment variable.
Provide window.location.origin as the base when constructing the URL from redirectAfter so relative paths are resolved correctly. This prevents errors from the URL constructor for relative redirectAfter values and ensures the success query param and redirect_after value are set to a full URL.
|
New azure vertex changes available for preview here |
There was a problem hiding this comment.
Pull request overview
This PR refactors Vertex’s API URL construction and OAuth flow to avoid localhost fallbacks baked into the client bundle, and to reduce redirect-loop issues by improving session synchronization and proxy path normalization.
Changes:
- Introduces centralized API URL builders for server (
buildServerApiUrl) and browser (buildBrowserApiUrl) usage. - Tightens API base URL env validation (fail-fast when
NEXT_PUBLIC_API_URLis missing) and updates multiple call sites to use the new routing helpers. - Improves OAuth token handoff/session sync and increases OAuth profile fetch timeout with cleaner abort handling.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| src/vertex/vertex.config.ts | Switches config API base URL sourcing to getApiBaseUrl() (strict env). |
| src/vertex/lib/envConstants.ts | Removes localhost fallback behavior and enforces NEXT_PUBLIC_API_URL presence. |
| src/vertex/lib/api-routing.ts | Adds server/browser API URL builders, enabling relative routing on the client. |
| src/vertex/core/utils/proxyClient.ts | Updates proxy URL building and avoids duplicated /v2 segments. |
| src/vertex/core/services/network-service.ts | Migrates network service endpoints to the new server URL builder. |
| src/vertex/core/auth/oauth-session.ts | Updates OAuth initiation URL building (currently still server-based). |
| src/vertex/core/auth/authProvider.tsx | Improves token handoff/session update sequencing to prevent redirect loops. |
| src/vertex/core/apis/users.ts | Migrates login endpoint URL building to the new server URL builder. |
| src/vertex/components/features/auth/social-auth-section.tsx | Adjusts redirect_after to include success=<provider> and adds an env-based guard (problematic). |
| src/vertex/app/changelog.md | Documents release notes for the routing/OAuth changes. |
| src/vertex/app/api/auth/[...nextauth]/options.ts | Increases OAuth profile fetch timeout, normalizes tokens, and handles aborts cleanly. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Switch oauth-session to use buildBrowserApiUrl for constructing the OAuth initiation URL (client-side) instead of buildServerApiUrl. Remove the environment-var guard in SocialAuthSection that hid social auth when NEXT_PUBLIC_API_URL was missing so social buttons render even if that env var isn't present. This change prevents unnecessary hiding and avoids runtime issues during OAuth initiation by using the browser API URL builder. Files changed: src/vertex/core/auth/oauth-session.ts, src/vertex/components/features/auth/social-auth-section.tsx.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/vertex/core/services/network-service.ts (1)
22-27:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAdd request timeouts to axios calls used by server handlers.
Both axios requests run without a timeout. In server route flows, this can tie up request handling indefinitely when upstream is slow/unresponsive. Add
timeout: NETWORK_REQUEST_TIMEOUT_MSto both calls.Suggested patch
const response = await axios.get(url, { + timeout: NETWORK_REQUEST_TIMEOUT_MS, headers: { Authorization: token.startsWith("JWT ") ? token : `JWT ${token}`, "X-Auth-Type": "JWT" } }); ... const response = await axios.put(url, payload, { + timeout: NETWORK_REQUEST_TIMEOUT_MS, headers: { Authorization: token.startsWith("JWT ") ? token : `JWT ${token}`, "X-Auth-Type": "JWT" } });Also applies to: 69-74
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/vertex/core/services/network-service.ts` around lines 22 - 27, The axios.get calls in network-service.ts are missing timeouts; update both axios requests (the one that builds headers with Authorization: token.startsWith("JWT ") and the second call around lines 69-74) to include timeout: NETWORK_REQUEST_TIMEOUT_MS in the request options so server handlers can't hang indefinitely; ensure NETWORK_REQUEST_TIMEOUT_MS is referenced (or imported) and added alongside headers in each axios.get call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/vertex/core/services/network-service.ts`:
- Line 59: The URL composes dynamic path segments using id and action unescaped;
update the code that calls buildServerApiUrl so each path segment (id and
action) is safely encoded (e.g., wrap them with encodeURIComponent, optionally
trim) before interpolation, leaving the existing adminSecret encoding as-is, so
the status-update URL cannot be hijacked by reserved characters.
---
Outside diff comments:
In `@src/vertex/core/services/network-service.ts`:
- Around line 22-27: The axios.get calls in network-service.ts are missing
timeouts; update both axios requests (the one that builds headers with
Authorization: token.startsWith("JWT ") and the second call around lines 69-74)
to include timeout: NETWORK_REQUEST_TIMEOUT_MS in the request options so server
handlers can't hang indefinitely; ensure NETWORK_REQUEST_TIMEOUT_MS is
referenced (or imported) and added alongside headers in each axios.get call.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 83216de5-f27e-47ed-99aa-346a0eb5d0cf
📒 Files selected for processing (3)
src/vertex/components/features/auth/social-auth-section.tsxsrc/vertex/core/auth/oauth-session.tssrc/vertex/core/services/network-service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/vertex/core/auth/oauth-session.ts
- src/vertex/components/features/auth/social-auth-section.tsx
Hide the social auth UI when NEXT_PUBLIC_API_URL is not set to avoid runtime crashes during OAuth initiation. Also switch oauth-session to use buildServerApiUrl when constructing the /users/auth/:provider initiation URL to ensure the API base is built appropriately. Changes touch social-auth-section.tsx and oauth-session.ts.
|
New azure vertex changes available for preview here |
1 similar comment
|
New azure vertex changes available for preview here |
Allow the client to fully handle OAuth callbacks and preserve provider/redirect info. - Middleware: always return authorized so the client-side AuthWrapper enforces protection. This is required because OAuth uses URL hash fragments (e.g. #token=...) which server-side middleware cannot read; blocking here could strip callbacks and cause redirect loops. - Social auth: stop building a new URL and appending a success param; pass redirectAfter through as provided (redirect_after = redirectAfter). - OAuth session: if the provider is missing in the handoff, fall back to getLastUsedOAuthProvider() so provider info is retained when possible. These changes ensure OAuth flows and redirects are handled correctly on the client and that provider information is preserved.
|
New azure vertex changes available for preview here |
1 similar comment
|
New azure vertex changes available for preview here |
Description
This PR introduces a robust overhaul of how the application handles API routing and the OAuth authentication flow.
The core issue resolved here stems from build-time environment variables. Previously, if
NEXT_PUBLIC_ENVorNEXT_PUBLIC_API_URLwere missing during the Next.js build process, the fallback logic bakedhttp://localhost:3000directly into the production client bundle. This caused social login initiations to attempt routing throughlocalhost. We resolved this by shifting to relative browser routing, and simultaneously fixed subsequent edge-case bugs causing redirect loops and profile fetch timeouts.Final Outcome & Key Features
NEXT_PUBLIC_variables for client-side API requests. Browser API calls now use relative paths (/api/v2/...), natively resolving to the correct domain (production, staging, or local) without split-brain environment risks./loginpage after successful OAuth handoffs due to React context lag and middleware interceptions.AbortErrors to prevent noisy server logs.Technical Changes
API Routing & Proxy Stabilization (
api-routing.ts&proxyClient.ts)buildBrowserApiUrlwhich strictly returns relative paths for browser-side requests. This entirely bypasses thelocalhostfallback bug caused by missing build-time environment variables.buildServerApiUrlfor server-side requests. TightenedenvConstants.tssogetApiBaseUrl()strictly requiresNEXT_PUBLIC_API_URL, throwing a clear build error rather than silently falling back tolocalhost.v2/segments, preventing double/v2/v2/URL paths when proxying to the backend.Authentication & Session Sync (
authProvider.tsx,options.ts,social-auth-section.tsx)SocialAuthSectionnow safely appends asuccess=<provider>query parameter to theredirect_afterURL. This signals the NextAuth middleware to allow the OAuth callback to pass through without forcefully intercepting it.useEffectwatcher inTokenHandoffHandlerto strictly observe the session status. The UI now remains blocked (isHandlingOAuthstays true) until NextAuth fully broadcasts the authenticated state across the React context tree, preventing rogue client-side redirects to/login.Authorizationheaders are only appended when the token is actually present.Summary by CodeRabbit
New Features
Bug Fixes
Improvements
Documentation