> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ofauth.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Handle account reconnects

> Pause account actions when access expires and resume after the owner reconnects.

An expired OAuth access token and an expired OnlyFans session need different fixes. Refresh the access token through [Tokens and refresh](https://docs.ofauth.com/v3/api-reference/link/tokens.md). When an OnlyFans account needs a reconnect, create a targeted journey for its owner.

![Pause actions after the OnlyFans session expires. Ask the owner to reconnect, then read the current account record. Resume with the same account ID only when status is connected; otherwise follow current recovery.](https://mintcdn.com/ofauth/VVqOdSxbrh7mDF0M/images/v3/account-recovery.svg?fit=max\&auto=format\&n=VVqOdSxbrh7mDF0M\&q=85\&s=902c1c2ec6048700bd9b4080f60c0e7b)

Pause only the affected account. A successful token refresh does not change the OnlyFans account's reconnect status. Confirm current account status before resuming actions.

## Know who handles each step

| What happens | Who handles it |
| - | - |
| Access requires a reconnect | OFAuth reports the account state through API responses and lifecycle events. Your application pauses the affected account's actions. |
| The OnlyFans session needs restoring | The account owner reconnects in OFAuth. Your application directs the owner to reconnect. |
| The account reconnects | Your application reads its current status and resumes only when it is `connected`. |
| A write was interrupted | Your application checks whether it completed before sending it again. Reconnecting does not tell you whether that earlier action completed. |

## Detect an expired account

Pause actions for the affected linked account when a request returns `linked_account_reconnect_required`, its status is `needs_reconnect`, or you receive `linked_account.expired`.

Keep the account ID and authorization. Other linked accounts may still be usable.

## Ask the owner to reconnect

For an Express implementation, see the [customer integration source example](https://github.com/OFAuth-source/example-express-oauth). It includes app sessions, account selection, reconnect routes, and PostgreSQL storage.

Create a short-lived journey with the authorization's current access token:

```typescript theme={null}
const journey = await client.linkedAccounts.createReconnect({
  id: linkedAccountId,
  body: {
    redirect_uri: registeredReturnUrl,
    state: savedReconnectState
  }
})
// Send the owner's browser to journey.url.
```

Generate a random, one-use `state` and bind it to the initiating app session. `redirect_uri` must exactly match a callback registered for the OAuth client. Use the returned `url` rather than constructing a Link URL. The journey expires at `expires_at` and targets only `linked_account_id` under `authorization_id`.

If your auth library owns the OAuth callback, it will reject the reconnect return as an unknown OAuth state. Use a separate return URL instead:

* **Developer integration**: add the return URL to the integration's redirect URIs in the dashboard.
* **Operator private app**: register it as `ofauth_reconnect_return_uri` (see [Register a reconnect return URL](https://docs.ofauth.com/v3/guides/operator-apps.md#register-a-reconnect-return-url)). It is accepted only by reconnect, never as an OAuth redirect URI.

The owner authenticates to OFAuth and reconnects the exact account. The target and return URL cannot be changed during the journey. Reconnect retains the authorization, linked account ID, and scopes. Sandbox sample accounts use the dashboard's **Reconnect** action instead of provider sign-in.

## Handle the return

Keep reconnect state on your server. Bind each value to the app session, the token-storage key, and the linked account being restored. Create this table once:

```sql theme={null}
CREATE TABLE app_reconnect (
	state text PRIMARY KEY,
	session_id text NOT NULL,
	user_key text NOT NULL,
	linked_account_id text NOT NULL,
	expires_at timestamptz NOT NULL
);
```

Before opening the journey, insert a random state with its bindings. Keep the state for 30 minutes so an expired journey can still return a clear result. The journey itself expires at `expires_at` in the API response.

The return handler below uses the `pool` and `ofauth` from [Store customer tokens](https://docs.ofauth.com/v3/sdk/typescript.md#store-customer-tokens). Pass the current trusted app session from your server. Read the target account from the saved state, never from callback parameters.

```typescript theme={null}
import { OFAuthClient } from "@ofauth/onlyfans-sdk"

type ReconnectSession = {
	id: string
	userId: string
}

async function finishReconnect(
	request: Request,
	session: ReconnectSession | null
): Promise<Response> {
	if (!session) {
		return Response.json({ error: "Sign in and start reconnect again." }, { status: 401 })
	}

	const params = new URL(request.url).searchParams
	const state = params.get("state")
	if (!state || params.getAll("state").length !== 1) {
		return Response.json({ error: "Invalid reconnect return." }, { status: 400 })
	}

	const userKey = JSON.stringify([process.env.OFAUTH_CLIENT_ID!, session.userId])
	const { rows } = await pool.query<{ expires_at: Date; linked_account_id: string }>(`
		DELETE FROM app_reconnect
		WHERE state = $1 AND session_id = $2 AND user_key = $3
		RETURNING expires_at, linked_account_id
	`, [state, session.id, userKey])
	const saved = rows[0]
	if (!saved || saved.expires_at.getTime() <= Date.now()) {
		return Response.json({ error: "Reconnect return expired or already used." }, { status: 400 })
	}

	const outcome = params.get("reconnect")
	if (params.getAll("reconnect").length !== 1 ||
		!outcome || !["completed", "canceled", "expired", "denied"].includes(outcome)) {
		return Response.json({ error: "Invalid reconnect outcome." }, { status: 400 })
	}

	const client = new OFAuthClient({ accessToken: async () => currentAccessToken(userKey) })
	const account = await client.linkedAccounts.get({ id: saved.linked_account_id })
	const messages: Record<string, string> = {
		completed: "Reconnect finished.",
		canceled: "Reconnect canceled. You can try again.",
		expired: "Reconnect expired. Start a new reconnect.",
		denied: "Reconnect was denied. Start again when you are ready."
	}
	return Response.json({
		message: messages[outcome],
		linkedAccountId: account.id,
		status: account.status,
		canResume: outcome === "completed" && account.status === "connected"
	})
}
```

`currentAccessToken` is your auth framework or application’s token getter. Mount this handler at your registered return URL, outside the auth library's OAuth callback route. If the app session has expired, ask the user to sign in and start a new journey. A callback from another session or a repeated callback cannot consume a valid pending return. If the user selects another account during reconnect, this handler still checks the original target.

The handler checks the current account for every valid outcome. Resume actions only when `canResume` is `true`. If the lookup fails, keep the account paused and follow the error's recovery action. An account may still need attention even when the return says `completed`.

The source example includes the Express route, the state insert, and app-session storage. For access-token recovery, see [Handle failures](https://docs.ofauth.com/v3/sdk/typescript.md#handle-failures).

## Resume actions

After you receive `linked_account.reconnected`, call `GET /v3/linked-accounts/{id}` with the authorization's access token. Resume when its status is `connected`. The linked account ID stays the same.

If the account was removed or the authorization revoked, follow the error's recovery action to request access again. See [Manage linked accounts](https://docs.ofauth.com/v3/guides/linked-accounts.md).

Before resending an action interrupted by a network failure, check whether it completed. See [Handle failed requests](https://docs.ofauth.com/v3/reference/error-handling.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.