Skip to content

Conversation

dtoxvanilla1991
Copy link

@dtoxvanilla1991 dtoxvanilla1991 commented Aug 5, 2025

initRef.current flag was being set after an asynchronous call (await checkAuth(...)), both invocations of init could proceed before the flag was updated, leading to the exchangeAuthCode function being called twice.

Explain your changes

The root cause of the double token exchange request appears to be the race condition within the init function in KindeProvider.tsx. React's StrictMode causes the useEffect that calls init to run twice. Because the initRef.current flag was being set after an asynchronous call (await checkAuth(...)), both invocations of init could proceed before the flag was updated, leading to the exchangeAuthCode function being called twice.

To fix this, I've moved the line initRef.current = true; to before the await checkAuth({ domain, clientId }); call. This ensures that the flag is set synchronously, preventing the second invocation from executing the token exchange logic.

Checklist

🛟 If you need help, consider asking for advice over in the Kinde community.

initRef.current flag was being set after an asynchronous call (await checkAuth(...)), both invocations of init could proceed before the flag was updated, leading to the exchangeAuthCode function being called twice.
Copy link

coderabbitai bot commented Aug 5, 2025

Walkthrough

Moved the init guard setting (initRef.current = true) to occur before awaiting checkAuth({ domain, clientId }) in KindeProvider.tsx to prevent concurrent re-entrancy. No public APIs changed; URL parameter and error handling flows remain as before.

Changes

Cohort / File(s) Summary
Provider init guard reordering
src/state/KindeProvider.tsx
Set initRef.current = true before invoking await checkAuth to prevent multiple concurrent initializations; no API or behavior changes beyond guard timing.

Sequence Diagram(s)

sequenceDiagram
  actor App
  participant KindeProvider
  participant AuthService as checkAuth

  Note over KindeProvider: New flow
  App->>KindeProvider: init()
  KindeProvider->>KindeProvider: initRef.current = true
  KindeProvider->>AuthService: checkAuth(domain, clientId)
  AuthService-->>KindeProvider: result
  KindeProvider-->>App: init complete
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Possibly related PRs

Suggested reviewers

  • DaveOrDead
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dtoxvanilla1991 dtoxvanilla1991 marked this pull request as ready for review August 13, 2025 10:29
Copy link

@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: 1

🧹 Nitpick comments (3)
src/state/KindeProvider.tsx (3)

487-499: Avoid second code exchange on StrictMode remount by stripping auth params before invoking callbacks

On success, you currently rely on the default onSuccess to clear the URL. If a consumer overrides onSuccess without removing query params, a StrictMode remount can re-run init and try to exchange the same code again. Unconditionally strip known auth params before invoking onSuccess.

Apply this diff:

         if (codeResponse.success) {
           const user = await getUserProfile();
           if (user) {
             setState((val) => ({ ...val, user, isAuthenticated: true }));
+            // Always remove auth-related query params to prevent re-exchange on remounts (e.g., React StrictMode)
+            try {
+              const url = new URL(window.location.href);
+              const sp = new URLSearchParams(url.search);
+              sp.delete("code");
+              sp.delete("state");
+              sp.delete("reauth_state");
+              sp.delete("error");
+              sp.delete("error_description");
+              url.search = sp.toString();
+              window.history.replaceState({}, document.title, url.toString());
+            } catch (_) {
+              // no-op: URL manipulation best-effort
+            }
             mergedCallbacks.onSuccess?.(
               user,
               {
                 ...returnedState,
                 kinde: undefined,
               },
               contextValue,
             );

625-635: Reduce unnecessary re-executions of init effect

Because init depends on contextValue (which depends on state), every state change recreates init and re-triggers this effect. The ref guard blocks re-entry, but the effect still churns. If you don’t need to re-run init when props change, run it once on mount.

Apply this diff:

-  useEffect(() => {
-    const mounted = { current: true };
-
-    if (mounted.current) {
-      init();
-    }
-
-    return () => {
-      mounted.current = false;
-    };
-  }, [init]);
+  useEffect(() => {
+    init();
+    // Run only once on mount; initRef prevents any accidental re-entry.
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, []);

If you do need to respond to dynamic prop changes (domain/clientId), keep the current approach but consider storing only those props in the dependency list (and remove contextValue) to minimize re-runs.


455-466: Potential base64url decoding mismatch for state

state is encoded with base64UrlEncode, but decoded using atob, which expects standard Base64. If base64url padding or url-safe chars appear, atob may throw. Consider decoding as base64url.

Example patch:

-      const decoded = atob(searchParams.get("state") || "");
+      const rawState = searchParams.get("state") || "";
+      const decoded = (() => {
+        try {
+          // Convert base64url -> base64 and pad
+          const b64 = rawState.replace(/-/g, "+").replace(/_/g, "/");
+          const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
+          return atob(padded);
+        } catch {
+          return "";
+        }
+      })();

Please verify whether base64UrlEncode indeed produces URL-safe Base64 (it likely does). If so, the above guards against malformed/URL-safe inputs without relying on consumer callbacks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d92895 and ac83aeb.

📒 Files selected for processing (1)
  • src/state/KindeProvider.tsx (1 hunks)
🔇 Additional comments (1)
src/state/KindeProvider.tsx (1)

553-556: Good fix: moving the init guard before the await prevents concurrent re-entry

Setting initRef.current = true before awaiting checkAuth closes the race where init could be re-entered (due to state-driven re-renders and StrictMode dev behavior) and perform a second token exchange. This is the correct place for the guard.

Comment on lines 555 to 557
initRef.current = true;
await checkAuth({ domain, clientId });
const params = new URLSearchParams(window.location.search);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling around checkAuth to avoid stuck loading state or silent failures

If checkAuth throws, init will abort before setting isLoading to false or proceeding to other branches. Catch and surface the error, but continue initialization so subsequent logic can still run.

Apply this diff:

   if (initRef.current) return;
   initRef.current = true;
-  await checkAuth({ domain, clientId });
+  try {
+    await checkAuth({ domain, clientId });
+  } catch (error) {
+    console.error("checkAuth error:", error);
+    mergedCallbacks.onError?.(
+      { error: "ERR_CHECK_AUTH", errorDescription: String(error) },
+      {},
+      contextValue,
+    );
+    // Intentionally continue; subsequent logic will determine auth state and set isLoading.
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
initRef.current = true;
await checkAuth({ domain, clientId });
const params = new URLSearchParams(window.location.search);
if (initRef.current) return;
initRef.current = true;
try {
await checkAuth({ domain, clientId });
} catch (error) {
console.error("checkAuth error:", error);
mergedCallbacks.onError?.(
{ error: "ERR_CHECK_AUTH", errorDescription: String(error) },
{},
contextValue,
);
// Intentionally continue; subsequent logic will determine auth state and set isLoading.
}
const params = new URLSearchParams(window.location.search);
🤖 Prompt for AI Agents
In src/state/KindeProvider.tsx around lines 555 to 557, wrap the await
checkAuth({ domain, clientId }) call in a try/catch so thrown errors don’t abort
initialization; on catch, record or log the error (e.g. set an error state or
processLogger.error) and ensure isLoading is set to false (or otherwise clear
loading) before continuing, then let the function proceed to the subsequent
logic (parsing URLSearchParams and other branches) so the component won’t remain
stuck in a loading state or silently fail.

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