Why Connecting a Solana Wallet on iPhone Signs Users Out, and How to Fix It
ยท 15 min read
If your Solana web app lets people sign in with Google or Apple before they connect a wallet, try this on an iPhone. Sign in, tap Connect Wallet and pick Phantom. You'd expect Phantom's "Connect" approval screen. Instead, Phantom opens its own built-in browser and loads your site from scratch, and the user isn't signed in there. Whatever they were in the middle of is gone, and they have to sign in again inside a browser they never chose to open.
I ran into this on a project where users sign in with Google or Apple and then connect Phantom or Solflare. On desktop, the wallet extension handled it fine. On iPhone, connecting a wallet signed the user out and lost whatever they were doing.
This article explains why the Solana wallet adapter behaves this way, and how I fixed it with the wallets' own deep-link protocol. The encryption turned out to be the small part. The harder part is that the wallet can send the user back to a different browser from the one they left, so nothing your app needs after the round trip can live in that browser. The examples assume you're using @solana/wallet-adapter-react and have a server you can add a few endpoints and two database tables to.
When the Phantom adapter from @solana/wallet-adapter-phantom is created, it checks whether it's running on iOS in a browser it can redirect. The check lives in @solana/wallet-adapter-base:
export function isIosAndRedirectable() {
if (!navigator) return false;
const userAgent = navigator.userAgent.toLowerCase();
const isIos = userAgent.includes('iphone') || userAgent.includes('ipad');
const isSafari = userAgent.includes('safari');
return isIos && isSafari;
}
If that returns true, the adapter marks itself as Loadable. Then, when your app calls connect(), it doesn't open Phantom's approval screen. It sends the whole tab to a Phantom link:
if (this.readyState === WalletReadyState.Loadable) {
const url = encodeURIComponent(window.location.href);
const ref = encodeURIComponent(window.location.origin);
window.location.href = `https://phantom.app/ul/browse/${url}?ref=${ref}`;
return;
}
ul/browse is Phantom's universal link for "open this URL in Phantom's in-app browser". The reasoning makes sense: mobile Safari can't run wallet extensions, so the only way to give the page a Phantom provider is to reopen it inside Phantom, where one gets injected. The Solflare adapter does the same thing with https://solflare.com/ul/v1/browse/. It isn't only Safari, either. Chrome, Firefox and Edge on iOS all include "Safari" in their user agents, and a comment in the adapter's source says it counts on that, so every iPhone browser takes this path.
The problem is what the user loses on the way. Phantom's in-app browser is a separate browsing context, with its own cookies and localStorage. Your sign-in session, your app's state and anything the user picked before tapping the button stay behind in Safari. For an anonymous visitor browsing a dApp, that's a fair trade. For a signed-in user in the middle of something, it breaks the flow.
My first fix kept the redirect and carried the login with it. I subclassed both adapters and overrode connect(), so that for a signed-in user on iOS, it creates a one-time handoff on the server before redirecting:
export class HandoffPhantomWalletAdapter extends PhantomWalletAdapter {
override async connect(): Promise<void> {
if (this.connected || this.connecting) return;
if (this.readyState === WalletReadyState.Loadable && isIosAndRedirectable()) {
await redirectViaHandoff('phantom');
return;
}
return super.connect();
}
}
The handoff link opens a /handoff/<id> page inside Phantom's browser. That page asks the server to consume the handoff, which works only once and only for 10 minutes, and gets back a short-lived sign-in token that logs the user in on arrival. The first version put that sign-in token straight in the URL. I later replaced it with the handoff ID, so no login token ever appears in a URL, where it could end up in browser history.
This made the redirect survivable, and it's still in the app as an "Open in Phantom app" fallback. But the user still ends up browsing my site inside Phantom instead of in the browser they chose, so it wasn't the real fix.
ul/browse isn't the only universal link Phantom publishes. There's also a Connect link, https://phantom.app/ul/v1/connect, that opens the Phantom app itself and shows its approval screen, with no browser involved. Your app creates an encryption key pair, sends the public key in the link along with a redirect_link, and when the user approves, Phantom opens your redirect_link with an encrypted response. Solflare has the same protocol at https://solflare.com/ul/v1/connect, with the same parameters and the same nacl.box encryption, so supporting both wallets costs little more than supporting one.
There are other ways to reach a mobile wallet. WalletConnect (through Reown AppKit) keeps the result off the redirect entirely by syncing it over a relay, but it adds a third-party service and a project ID, and only works with wallets that support it. Solana's Mobile Wallet Adapter (MWA) talks to wallet apps directly through Android intents, so it needs no redirect at all, but it doesn't exist on iOS.
I didn't pick just one. The app chooses a "lane" for each browser:
| Lane |
When |
How it connects |
| Extension |
A wallet is already injected (desktop extension, or the wallet's own browser) |
The normal adapter flow |
| MWA |
Android Chrome with no extension |
Mobile Wallet Adapter, no redirect |
| Deep link |
Other mobile browsers, which in practice means iPhone |
The wallet's ul/v1 deep links |
Solflare only uses the deep-link lane on iOS. On Android and desktop, its adapter opens an in-page web wallet without leaving the site, so routing it through deep links would break something that already worked. One more detail: on the iOS deep-link lane, the app never calls SolflareWalletAdapter.connect() or PhantomWalletAdapter.connect(), because that fires the adapter's own ul/browse redirect and brings the original bug back.
This is the detail that shaped the rest of the design. The redirect_link you give the wallet is a normal https:// URL, and iOS opens https links that come from another app in the default browser. So a user who starts in Chrome on their iPhone and approves in Phantom comes back in Safari. Safari has none of Chrome's cookies or storage. If you kept your encryption key in sessionStorage before leaving, it isn't there when the response arrives.
So I moved everything that has to survive the round trip to the server. There are two tables:
- Wallet sessions last across many round trips. Each one holds the app's encryption secret key, the wallet's encryption public key, the
session token Phantom returns, the wallet address, and the user it belongs to.
- Flows are one row per round trip. The row's ID goes into the return link, and the row holds the kind of request (connect, sign a transaction, sign a message), the context the screen needs afterwards (such as the path to return to), the result, a status, a 10-minute expiry and a
consumed_at timestamp.
The browser only ever sees the flow ID, and the secret key never leaves the server.
Here's the connect endpoint, trimmed down. The db calls stand in for your database client; I used Supabase:
const keyPair = nacl.box.keyPair();
const walletSession = await db.walletSessions.insert({
userId: user?.id ?? null,
email: user?.email ?? null,
dappSecretKey: toBase64(keyPair.secretKey),
provider,
});
const flowId = crypto.randomUUID().replace(/-/g, '');
await db.flows.insert({
id: flowId,
walletSessionId: walletSession.id,
kind: 'connect',
provider,
context: { returnPath },
});
const base = provider === 'solflare' ? 'https://solflare.com/ul/v1' : 'https://phantom.app/ul/v1';
const params = new URLSearchParams({
app_url: origin,
dapp_encryption_public_key: bs58.encode(keyPair.publicKey),
cluster,
redirect_link: `${origin}/phantom-callback?s=${flowId}`,
});
return Response.json({ url: `${base}/connect?${params}`, walletSessionId: walletSession.id });
On the client, the connect button calls this endpoint, stores the walletSessionId in localStorage as a shortcut for this browser, and sets window.location.href to the returned URL. The page is about to unload, so nothing after that line matters.
When the user approves, Phantom opens /phantom-callback?s=<flowId> with three more query parameters: phantom_encryption_public_key, nonce and data. Solflare sends the same thing, except the first one is called solflare_encryption_public_key. If the user rejects the request, you get errorCode and errorMessage instead.
The callback route has to sit outside whatever guard protects your signed-in pages. The browser it lands in might have no session at all, and an auth guard would redirect to your sign-in page before the callback could do anything. The page itself does very little. It forwards the parameters to the server and says whether this browser is signed in:
const params = new URLSearchParams(window.location.search);
const { data: userData } = await supabase.auth.getUser();
const needsSession = !userData?.user;
const res = await fetch('/api/wallet/resolve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
s: params.get('s'),
phantom_encryption_public_key: params.get('phantom_encryption_public_key') ?? undefined,
solflare_encryption_public_key: params.get('solflare_encryption_public_key') ?? undefined,
nonce: params.get('nonce') ?? undefined,
data: params.get('data') ?? undefined,
errorCode: params.get('errorCode') ?? undefined,
errorMessage: params.get('errorMessage') ?? undefined,
needsSession,
}),
});
On the server, the resolve endpoint does four things in order.
First, it claims the flow with a single conditional update, so a replayed or doubled callback can't process the same response twice:
const claimed = await db.flows.update(
{ consumedAt: now },
{ where: { id: s, consumedAt: null, expiresAt: { gt: now } } },
);
if (!claimed) return new Response('Flow already used', { status: 410 });
Second, it decrypts the response with the secret key it kept. For a connect, the wallet's key comes from the callback parameters. For a signing request, it's the one saved on the wallet session during connect:
const walletKey =
flow.kind === 'connect'
? flow.provider === 'solflare'
? body.solflare_encryption_public_key
: body.phantom_encryption_public_key
: walletSession.walletEncryptionPublicKey;
const shared = nacl.box.before(bs58.decode(walletKey), fromBase64(walletSession.dappSecretKey));
const opened = nacl.box.open.after(bs58.decode(body.data), bs58.decode(body.nonce), shared);
if (!opened) throw new Error('Could not decrypt the wallet response');
const decrypted = JSON.parse(new TextDecoder().decode(opened));
Third, it saves the result. For a connect, that's the wallet's encryption public key, the session token and the wallet address (decrypted.public_key), all on the wallet session row, because every later signing request needs them.
Fourth, if the browser said it has no session, it mints a one-time sign-in token for the user the wallet session belongs to. With Supabase, that's auth.admin.generateLink({ type: 'magiclink', email }), and the callback page redeems the returned token_hash with supabase.auth.verifyOtp(). This is what makes the different-browser case work. The user who left Chrome and landed in Safari is signed in by the time the page moves on.
Back in the browser, the callback page stores the result in localStorage, removes the flow ID and the wallet's parameters from the address bar with history.replaceState(), and navigates to the return path from the flow's context.
Signing works the same way as connecting, with a new flow row per request. The server encrypts the payload with the shared secret from connect and a fresh 24-byte nonce, and builds a link to /ul/v1/signTransaction or /ul/v1/signMessage:
const shared = nacl.box.before(
bs58.decode(walletSession.walletEncryptionPublicKey),
fromBase64(walletSession.dappSecretKey),
);
const nonce = nacl.randomBytes(24);
const payload = { transaction: base58Tx, session: walletSession.session };
const data = nacl.box.after(new TextEncoder().encode(JSON.stringify(payload)), nonce, shared);
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappPublicKey),
nonce: bs58.encode(nonce),
redirect_link: `${origin}/phantom-callback?s=${flowId}`,
payload: bs58.encode(data),
});
const url = `${base}/signTransaction?${params}`;
My first version used signAndSendTransaction, so Phantom would sign the transaction and submit it to the network in one step. Then signing requests from iPhone started failing with "This method is not supported". Phantom's docs now mark the signAndSendTransaction deep link as deprecated and point you to signTransaction instead. With sign-only, the wallet returns the signed transaction, and your server broadcasts it.
That change adds a risk: the callback page can be reloaded, and you don't want a reload to send the transaction twice. So the resolve endpoint reads the transaction's signature from the signed bytes and saves it on the flow row before broadcasting:
const signedTx = bs58.decode(decrypted.transaction);
const signature = firstSignatureOf(signedTx);
await db.flows.update({ result: { signature } }, { where: { id: flow.id } });
await broadcastSignedTransaction(signedTx);
When a callback comes in for a flow that's already consumed but completed with a signature, the endpoint returns that saved result instead of "Flow already used". A reload shows the same outcome, and nothing is sent to the network again.
One thing I couldn't find documented: when I tested on devnet, signing links failed with error code -32603 ("Unexpected error"). So on devnet, I send the user to sign inside the wallet's browser using the handoff from earlier, and keep signing links for mainnet.
None of this helps unless the screen that started the request knows how to finish it. A normal await wallet.signTransaction(...) can't return anything here, because the page that called it has unloaded by the time the wallet answers. So each flow that signs something is split in two: everything up to the signature, and everything after it.
The screen that asked for a signature checks for a stored result when it mounts, before it assumes the user is starting fresh:
useEffect(() => {
const pending = takeWalletResult((r) => r.kind === 'sign_transaction');
if (!pending) return;
if (pending.error) {
showError(pending.error);
return;
}
if (pending.result?.signature) {
continueAfterSignature(pending.result.signature, pending.context);
}
}, []);
takeWalletResult() reads the stored result and clears it. It takes a predicate because more than one component can be on screen when the user comes back. In my case, a component that handles Sign In With Solana could be mounted on the same screen and signs messages too, so each one claims only the results that belong to it. Sign In With Solana needed one more change: its nonce expires after five minutes, which is easy to exceed while the user is in the wallet, so the resume path requests a fresh nonce when the old one has run out.
Restoring the login covers the user who comes back in Safari, but they're still in a different browser from the one they chose. iPhone browsers have their own URL schemes, so for users who didn't start in Safari, the server wraps the callback URL in their browser's scheme before giving it to the wallet:
if (ua.includes('CriOS')) return callbackUrl.replace(/^https:\/\//, 'googlechromes://');
if (ua.includes('FxiOS')) return `firefox://open-url?url=${encodeURIComponent(callbackUrl)}`;
if (ua.includes('EdgiOS')) return callbackUrl.replace(/^https:\/\//, 'microsoft-edge-https://');
return callbackUrl;
I treat this as best effort. Neither wallet documents whether it follows a non-https return link. Brave on iPhone can't be detected at all, since its user agent looks like Safari's. So there are two safety nets. If a signing request comes back with an unexpected error after using a custom-scheme link, the server switches that wallet session to plain https links and asks the user to try again. And whichever browser the user lands in, the server-side restore still signs them in.
The same site also runs inside an Android app that wraps it in a WebView. There, deep links make things worse: the wallet's https return link opens in the system browser, not in the app. The fix inside the shell is to skip both the redirecting adapters and the deep-link lane, and sign directly through Mobile Wallet Adapter, which never leaves the app. The site detects the shell from its user agent (; wv) for an Android WebView, or a custom app name the shell adds).
If you want deep links to return into your own native app, the operating system has to know that your app owns your domain. That means iOS Universal Links and Android App Links, which need files hosted on your domain and a new native build. I didn't need them, because Mobile Wallet Adapter covered the Android shell.
The wallet adapter isn't wrong to send iPhone users to Phantom's browser. For an anonymous visitor, that's a reasonable way to get a wallet onto the page. It's only wrong when the user has a session and some progress you don't want to lose.
If that's your situation, here's the short version:
- Connect with the wallet's
ul/v1/connect deep link instead of ul/browse, and don't call the stock adapter's connect() on that path.
- Assume the response can land in a different browser. Keep the encryption keys and each pending request on your server, keyed by a flow ID in the return link, and restore the user's login with a one-time token when it arrives signed out.
- Claim each flow once, save results before side effects like a broadcast, and make a reloaded callback harmless.
- Use
signTransaction and broadcast yourself, since signAndSendTransaction is deprecated for deep links.
- On Android, use Mobile Wallet Adapter where you can, so there's no redirect at all.
The same lesson applies to any flow where control leaves your app and comes back through a URL, like OAuth or a payment redirect: don't count on coming back to the same browser you left.