Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/add-signin-reset.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add `reset` method to the sign-in resource.
6 changes: 6 additions & 0 deletions .changeset/cozy-webs-matter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add `reset` method to the new signUp resource.
17 changes: 17 additions & 0 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import {
clerkVerifyWeb3WalletCalledBeforeCreate,
} from '../errors';
import { eventBus } from '../events';
import { signInErrorSignal, signInResourceSignal } from '../signals';
import { BaseResource, UserData, Verification } from './internal';

export class SignIn extends BaseResource implements SignInResource {
Expand Down Expand Up @@ -1247,6 +1248,22 @@ class SignInFuture implements SignInFutureResource {
});
}

/**
* Resets the current sign-in attempt by clearing all local state back to null.
* Unlike other methods, this does NOT emit resource:fetch with 'fetching' status,
* allowing for smooth UI transitions without loading states.
*/
reset(): Promise<{ error: ClerkError | null }> {
// Clear errors
signInErrorSignal({ error: null });

// Create a fresh null SignIn instance and update the signal directly
const freshSignIn = new SignIn(null);
signInResourceSignal({ resource: freshSignIn });

return Promise.resolve({ error: null });
}
Comment on lines +1251 to +1265
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Reset leaves existing SignInFuture instances stale

reset() only swaps global signals; the current SignInFuture still points to the old SignIn (and retains #hasBeenFinalized). Callers that keep the instance can keep operating on stale state right after reset, which conflicts with the “reset current sign-in attempt” contract. Consider rebinding the future to the fresh resource or explicitly returning/invalidating the old instance to avoid stale usage.

🤖 Prompt for AI Agents
In `@packages/clerk-js/src/core/resources/SignIn.ts` around lines 1251 - 1265,
reset() currently swaps the global signals but leaves any existing SignInFuture
instances bound to the old SignIn (so callers keep stale state); modify reset()
to also rebind or invalidate those futures: after creating freshSignIn and
calling signInResourceSignal({ resource: freshSignIn }), iterate or access the
current SignInFuture(s) associated with the previous resource (the one
referenced by SignInFuture) and either (a) update their internal resource
reference to freshSignIn (rebind) or (b) set their internal finalized/invalid
flag (e.g., `#hasBeenFinalized` or an .invalidate() method) so they no longer
operate on the old SignIn; ensure the code updates or exposes the new
SignInFuture where callers expect it so no caller continues to operate on stale
state.


private selectFirstFactor(
params: Extract<SelectFirstFactorParams, { strategy: 'email_code' }>,
): EmailCodeFactor | null;
Expand Down
17 changes: 17 additions & 0 deletions packages/clerk-js/src/core/resources/SignUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
clerkVerifyWeb3WalletCalledBeforeCreate,
} from '../errors';
import { eventBus } from '../events';
import { signUpErrorSignal, signUpResourceSignal } from '../signals';
import { BaseResource, SignUpVerifications } from './internal';

declare global {
Expand Down Expand Up @@ -975,6 +976,22 @@ class SignUpFuture implements SignUpFutureResource {
await SignUp.clerk.setActive({ session: this.#resource.createdSessionId, navigate });
});
}

/**
* Resets the current sign-up attempt by clearing all local state back to null.
* Unlike other methods, this does NOT emit resource:fetch with 'fetching' status,
* allowing for smooth UI transitions without loading states.
*/
reset(): Promise<{ error: ClerkError | null }> {
// Clear errors
signUpErrorSignal({ error: null });

// Create a fresh null SignUp instance and update the signal directly
const freshSignUp = new SignUp(null);
signUpResourceSignal({ resource: freshSignUp });

return Promise.resolve({ error: null });
}
}

class SignUpEnterpriseConnection extends BaseResource implements SignUpEnterpriseConnectionResource {
Expand Down
70 changes: 70 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/SignIn.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../events';
import { signInErrorSignal, signInResourceSignal } from '../../signals';
import { BaseResource } from '../internal';
import { SignIn } from '../SignIn';

Expand Down Expand Up @@ -1890,5 +1892,73 @@ describe('SignIn', () => {
await expect(signIn.__internal_future.finalize()).rejects.toThrow();
});
});

describe('reset', () => {
afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
// Reset signals to initial state
signInResourceSignal({ resource: null });
signInErrorSignal({ error: null });
});

it('does NOT emit resource:fetch with status fetching', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const mockFetch = vi.fn();
BaseResource._fetch = mockFetch;

const signIn = new SignIn({ id: 'signin_123', status: 'needs_first_factor' } as any);
await signIn.__internal_future.reset();

// Verify that resource:fetch was NOT called with status: 'fetching'
const fetchingCalls = emitSpy.mock.calls.filter(
call => call[0] === 'resource:fetch' && call[1]?.status === 'fetching',
);
expect(fetchingCalls).toHaveLength(0);
// Verify no API calls were made
expect(mockFetch).not.toHaveBeenCalled();
});

it('clears any previous errors by updating signInErrorSignal', async () => {
// Set an initial error
signInErrorSignal({ error: new Error('Previous error') });
expect(signInErrorSignal().error).toBeTruthy();

const signIn = new SignIn({ id: 'signin_123', status: 'needs_first_factor' } as any);
await signIn.__internal_future.reset();

// Verify that error signal was cleared
expect(signInErrorSignal().error).toBeNull();
});

it('returns error: null on success', async () => {
const signIn = new SignIn({ id: 'signin_123', status: 'needs_first_factor' } as any);
const result = await signIn.__internal_future.reset();

expect(result).toHaveProperty('error', null);
});

it('resets an existing signin with data to a fresh null state', async () => {
const signIn = new SignIn({
id: 'signin_123',
status: 'needs_first_factor',
identifier: '[email protected]',
} as any);

// Verify initial state
expect(signIn.id).toBe('signin_123');
expect(signIn.status).toBe('needs_first_factor');
expect(signIn.identifier).toBe('[email protected]');

await signIn.__internal_future.reset();

// Verify that signInResourceSignal was updated with a new SignIn(null) instance
const updatedSignIn = signInResourceSignal().resource;
expect(updatedSignIn).toBeInstanceOf(SignIn);
expect(updatedSignIn?.id).toBeUndefined();
expect(updatedSignIn?.status).toBeNull();
expect(updatedSignIn?.identifier).toBeNull();
});
});
});
});
74 changes: 74 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/SignUp.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../events';
import { signUpErrorSignal, signUpResourceSignal } from '../../signals';
import { BaseResource } from '../internal';
import { SignUp } from '../SignUp';

Expand Down Expand Up @@ -701,5 +703,77 @@ describe('SignUp', () => {
expect(result.error).toBeInstanceOf(Error);
});
});

describe('reset', () => {
afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
// Reset signals to initial state
signUpResourceSignal({ resource: null });
signUpErrorSignal({ error: null });
});

it('does NOT emit resource:fetch with status fetching', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const mockFetch = vi.fn();
BaseResource._fetch = mockFetch;

const signUp = new SignUp({ id: 'signup_123', status: 'missing_requirements' } as any);
await signUp.__internal_future.reset();

// Verify that resource:fetch was NOT called with status: 'fetching'
const fetchingCalls = emitSpy.mock.calls.filter(
call => call[0] === 'resource:fetch' && call[1]?.status === 'fetching',
);
expect(fetchingCalls).toHaveLength(0);
// Verify no API calls were made
expect(mockFetch).not.toHaveBeenCalled();
});

it('clears any previous errors by updating signUpErrorSignal', async () => {
// Set an initial error
signUpErrorSignal({ error: new Error('Previous error') });
expect(signUpErrorSignal().error).toBeTruthy();

const signUp = new SignUp({ id: 'signup_123', status: 'missing_requirements' } as any);
await signUp.__internal_future.reset();

// Verify that error signal was cleared
expect(signUpErrorSignal().error).toBeNull();
});

it('returns error: null on success', async () => {
const signUp = new SignUp({ id: 'signup_123', status: 'missing_requirements' } as any);
const result = await signUp.__internal_future.reset();

expect(result).toHaveProperty('error', null);
});

it('resets an existing signup with data to a fresh null state', async () => {
const signUp = new SignUp({
id: 'signup_123',
status: 'missing_requirements',
email_address: '[email protected]',
first_name: 'John',
} as any);

// Verify initial state
expect(signUp.id).toBe('signup_123');
expect(signUp.emailAddress).toBe('[email protected]');
expect(signUp.firstName).toBe('John');

await signUp.__internal_future.reset();

// Verify that signUpResourceSignal was updated with a new SignUp(null) instance
const updatedSignUp = signUpResourceSignal().resource;
expect(updatedSignUp).toBeInstanceOf(SignUp);
expect(updatedSignUp?.id).toBeUndefined();
expect(updatedSignUp?.status).toBeNull();
expect(updatedSignUp?.emailAddress).toBeNull();
expect(updatedSignUp?.firstName).toBeNull();
expect(updatedSignUp?.lastName).toBeNull();
expect(updatedSignUp?.phoneNumber).toBeNull();
});
});
});
});
2 changes: 2 additions & 0 deletions packages/react/src/stateProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ export class StateProxy implements State {
password: this.gateMethod(target, 'password'),
sso: this.gateMethod(target, 'sso'),
finalize: this.gateMethod(target, 'finalize'),
reset: this.gateMethod(target, 'reset'),

emailCode: this.wrapMethods(() => target().emailCode, ['sendCode', 'verifyCode'] as const),
emailLink: this.wrapStruct(
Expand Down Expand Up @@ -268,6 +269,7 @@ export class StateProxy implements State {
ticket: gateMethod(target, 'ticket'),
web3: gateMethod(target, 'web3'),
finalize: gateMethod(target, 'finalize'),
reset: gateMethod(target, 'reset'),

verifications: wrapMethods(() => target().verifications, [
'sendEmailCode',
Expand Down
10 changes: 10 additions & 0 deletions packages/shared/src/types/signInFuture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,4 +519,14 @@ export interface SignInFutureResource {
* session state (such as the `useUser()` hook) to update automatically.
*/
finalize: (params?: SignInFutureFinalizeParams) => Promise<{ error: ClerkError | null }>;

/**
* Resets the current sign-in attempt by clearing all local state back to null.
* This is useful when you want to allow users to go back to the beginning of
* the sign-in flow (e.g., to change their identifier during verification).
*
* Unlike other methods, `reset()` does not trigger the `fetchStatus` to change
* to `'fetching'` and does not make any API calls - it only clears local state.
*/
reset: () => Promise<{ error: ClerkError | null }>;
}
10 changes: 10 additions & 0 deletions packages/shared/src/types/signUpFuture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,14 @@ export interface SignUpFutureResource {
* session state (such as the `useUser()` hook) to update automatically.
*/
finalize: (params?: SignUpFutureFinalizeParams) => Promise<{ error: ClerkError | null }>;

/**
* Resets the current sign-up attempt by clearing all local state back to null.
* This is useful when you want to allow users to go back to the beginning of
* the sign-up flow (e.g., to change their email address during verification).
*
* Unlike other methods, `reset()` does not trigger the `fetchStatus` to change
* to `'fetching'` and does not make any API calls - it only clears local state.
*/
reset: () => Promise<{ error: ClerkError | null }>;
}
Loading