Skip to content

fix: exchange the Keystatic Cloud authorization code only once - #1674

Open
theluckystrike wants to merge 1 commit into
Thinkmill:mainfrom
theluckystrike:fix-1671-cloud-code-once
Open

theluckystrike wants to merge 1 commit into
Thinkmill:mainfrom
theluckystrike:fix-1671-cloud-code-once

Conversation

@theluckystrike

Copy link
Copy Markdown

Fixes #1671

Signing in with Keystatic Cloud could end on Bad response: 400 {"error":"invalid_grant","error_description":"Invalid code"} even though the sign-in had worked.

The cause is in KeystaticCloudAuthCallback. The token exchange runs in a useEffect that depends on router, and RouterProvider builds a new router object on every render. Any re-render after the callback mounts runs the effect again with the same one-time code. The first POST /oauth/token succeeds and stores the token, the second is rejected with invalid_grant, and its setError replaces the screen with the error.

The fix keeps a useRef flag that is set before the request, so the code is exchanged once per callback no matter how often the effect re-runs. The rest of the flow (stored state, token storage, redirect to from) is unchanged.

Test: packages/keystatic/src/app/cloud-auth-callback.test.tsx renders the callback with a code and stored state, rerenders it with a fresh router object each time, and checks that fetch is called once, the redirect happens, the token is stored and no invalid_grant error is shown. On main it fails with expected "vi.fn()" to be called 1 times, but got 4 times, with this change it passes.

I ran npx vitest run --project keystatic (59 files, 708 passed, 8 skipped), npx tsc, and eslint and prettier on the changed files. I added a patch changeset for @keystatic/core.

@changeset-bot

changeset-bot Bot commented Nov 18, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: aa248ef

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@keystatic/core Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

This branch has not been deployed

No deployments
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.

Keystatic Cloud sign-in shows "invalid_grant: Invalid code" although sign-in succeeded (code exchanged twice)

1 participant