Skip to content

feat(react): support custom redirect function via AuthProvider#175

Merged
halvaradop merged 2 commits into
masterfrom
feat/add-custom-redirect
Jun 3, 2026
Merged

feat(react): support custom redirect function via AuthProvider#175
halvaradop merged 2 commits into
masterfrom
feat/add-custom-redirect

Conversation

@halvaradop
Copy link
Copy Markdown
Member

@halvaradop halvaradop commented Jun 2, 2026

Description

This pull request adds support for custom redirect handlers in authentication flows within the @aura-stack/react package.

Previously, authentication actions relied on the default browser navigation behavior. With this update, developers can provide their own redirect implementation, allowing seamless integration with framework-specific navigation APIs such as:

  • React Router
  • Next.js
  • TanStack Start
  • custom client-side routers

This provides greater flexibility when handling authentication redirects while preserving the existing default behavior.

Key Changes

  • Added support for custom redirect functions in authentication flows
  • Allow integration with framework-specific navigation APIs
  • Preserve default redirect behavior when no custom handler is provided
  • Improve flexibility for SPA and client-side routing environments

Usage

import type { PropsWithChildren } from "react"
import { AuthProvider } from "@aura-stack/react"

const Provider = ({ children }: PropsWithChildren) => {
  const redirect = (url: string) => {
    window.location.href = url
  }

  return (
    <AuthProvider redirect={redirect}>
      {children}
    </AuthProvider>
  )
}

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Jun 2, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
auth Skipped Skipped Jun 2, 2026 11:59pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors authentication redirect handling to move control from server-side routing to client-side React hooks. Core API types are unified into shared discriminated unions, client methods consistently request redirect: false, and React hooks handle navigation client-side using a configurable redirect callback or window.location.assign.

Changes

Client-side Redirect Refactoring

Layer / File(s) Summary
Type contract foundation
packages/core/src/@types/utility.ts, packages/core/src/@types/api.ts, packages/core/src/actions/signInCredentials/signInCredentials.ts
RequiredKeys utility and refactored return types (SignInCredentialsReturnData, SignOutReturnData, UpdateSessionReturnData) introduced. Client return types now use Extract to select the { redirect: false } subset from shared discriminated unions, and SignOutAPIOptions/UpdateSessionAPIOptions use RequiredKeys to require headers.
React context and redirect callback
packages/react/src/@types/types.ts, packages/react/src/context.tsx
AuthProviderProps gains optional redirect?: (url: string) => void | Promise<void> callback. Context interface exposes redirect from provider props, and AuthProvider destructures and provides it through context value.
Client request updates
packages/core/src/client/client.ts
signInCredentials, updateSession, and signOut now pass redirect: false in search parameters, shifting redirect authority from server router to client application.
React hooks redirect handling
packages/react/src/hooks.ts
Added performRedirect helper using context callback or window.location.assign. Updated useSignIn, useSignInCredentials, useUpdateSession, and useSignOut to call client methods with redirect: false and conditionally trigger performRedirect when hook options set redirect: true.
Hook tests and mock setup
packages/react/test/hooks.test.tsx
Test mocks updated to return redirect-related fields. New test scenarios validate redirect behavior with and without custom redirect callback, and confirm underlying client calls receive redirect: false.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • aura-stack-ts/auth#174: Refactor of core @types/api.ts redirect-related return types with shared *ReturnData aliases and Extract conditional selection, overlapping directly with the type contract changes in this PR.
  • aura-stack-ts/auth#117: Adjusts core auth signIn redirect contract and option/typing surfaces for redirect payload fields, providing the foundational type shapes this PR then uses for React hook redirect handling.
  • aura-stack-ts/auth#172: React context and hooks updates around session sync events (session:sync, session:update, session:clear) for cross-tab synchronization, overlapping with this PR's React context and hook refactoring.

Suggested labels

feature, enhancement, refactor

Poem

🐰 Redirects hop client-side now,
No server routing needed.
Hooks catch and navigate,
While callbacks spread like clover—
A hopping good refactor! 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(react): support custom redirect function via AuthProvider' accurately describes the main change—adding support for a custom redirect function through the AuthProvider component in the React package.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/add-custom-redirect

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/core/src/client/client.ts (2)

76-76: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Default redirect behavior may not match the documented @default true.

This branch (and the equivalents in signInCredentials, updateSession, signOut, and the React hooks) only performs navigation when options?.redirect === true. When redirect is omitted it is undefined, so no redirect occurs — yet OptionsWithRedirectTo.redirect is documented as @default true. If the default is intended to redirect, the guard should be options?.redirect !== false. Please confirm the intended default.

🤖 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 `@packages/core/src/client/client.ts` at line 76, The redirect check currently
only triggers when options?.redirect === true, so omitted redirects (undefined)
are treated as false; update the guard in the client.ts branch (and the
equivalent checks in signInCredentials, updateSession, signOut, and the React
hooks) to treat undefined as “true” by changing the condition to
options?.redirect !== false so redirect occurs by default; ensure every
occurrence that currently checks for === true is replaced with !== false and run
tests/verify navigation behavior after the change.

122-135: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Session payload (PII) leaked into query string.

Same pattern as credentials: searchParams: { ...options, redirect: false } spreads the full session object (e.g. user name/email) into the URL. The body already sends user/expires; only redirectTo/redirect belong in search params.

🔒️ Proposed fix
             searchParams: {
-                ...options,
+                redirectTo: options.redirectTo,
                 redirect: false,
             },
🤖 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 `@packages/core/src/client/client.ts` around lines 122 - 135, The session PATCH
is leaking PII by spreading the entire options/session into searchParams; update
the client.patch call in client.ts (the call to client.patch("/session")) to
only include allowed query keys (e.g. redirect and redirectTo) in searchParams
instead of spreading ...options or session. Ensure the request body still
contains user and expires (the existing body object remains), remove or replace
the spread in searchParams with an explicit object like { redirect: false,
redirectTo: options?.redirectTo } (or the minimal allowed keys), and keep the
X-CSRF-Token header intact.
🤖 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 `@packages/react/src/hooks.ts`:
- Around line 101-103: The current guard options?.redirect === true treats
undefined as false and therefore skips navigation even though redirect defaults
to true; change the condition to treat undefined as true (for example use
options?.redirect !== false or (options?.redirect ?? true) === true) where
performRedirect(redirect, value.signInURL) is called (symbols: options,
performRedirect, redirect, value.signInURL) in this hook and replicate the same
fix in the other three hooks so they honor the documented default; also align
the core client default-redirect logic (the root default-redirect concern) to
the same semantics so all callers behave consistently.

In `@packages/react/test/hooks.test.tsx`:
- Line 68: The test currently uses
expect(redirectMock).not.toHaveBeenCalledOnce(), which doesn't guarantee zero
calls; replace that assertion with expect(redirectMock).not.toHaveBeenCalled()
to precisely assert no redirect occurred; update the assertion in the test
referencing redirectMock in hooks.test.tsx (same test block) so it matches the
other tests' pattern.

---

Outside diff comments:
In `@packages/core/src/client/client.ts`:
- Line 76: The redirect check currently only triggers when options?.redirect ===
true, so omitted redirects (undefined) are treated as false; update the guard in
the client.ts branch (and the equivalent checks in signInCredentials,
updateSession, signOut, and the React hooks) to treat undefined as “true” by
changing the condition to options?.redirect !== false so redirect occurs by
default; ensure every occurrence that currently checks for === true is replaced
with !== false and run tests/verify navigation behavior after the change.
- Around line 122-135: The session PATCH is leaking PII by spreading the entire
options/session into searchParams; update the client.patch call in client.ts
(the call to client.patch("/session")) to only include allowed query keys (e.g.
redirect and redirectTo) in searchParams instead of spreading ...options or
session. Ensure the request body still contains user and expires (the existing
body object remains), remove or replace the spread in searchParams with an
explicit object like { redirect: false, redirectTo: options?.redirectTo } (or
the minimal allowed keys), and keep the X-CSRF-Token header intact.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 58f265c6-6c16-43b1-b8c3-8b82bff7c53c

📥 Commits

Reviewing files that changed from the base of the PR and between f49c924 and 1cf64ca.

📒 Files selected for processing (9)
  • packages/core/src/@types/api.ts
  • packages/core/src/@types/utility.ts
  • packages/core/src/actions/signInCredentials/signInCredentials.ts
  • packages/core/src/client/client.ts
  • packages/react/package.json
  • packages/react/src/@types/types.ts
  • packages/react/src/context.tsx
  • packages/react/src/hooks.ts
  • packages/react/test/hooks.test.tsx

Comment thread packages/react/src/hooks.ts
Comment thread packages/react/test/hooks.test.tsx
@halvaradop halvaradop merged commit 45fc929 into master Jun 3, 2026
7 checks passed
@halvaradop halvaradop deleted the feat/add-custom-redirect branch June 3, 2026 01:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant