Skip to main content
With Client Auth, Portal identifies your end user and creates their client for you, so you need neither a login system of your own nor a server-side call to mint a Client Session Token. The Web SDK’s model differs from every other Portal SDK in one important way, and the rest of this guide follows from it:
  • The Client Session Token never reaches your page. The SDK runs in a hidden iframe on the Portal origin, and the token stays there. portal.apiKey stays undefined.
  • portal.auth is the host-facing API. Every method except parseRedirect(), which reads a URL locally, proxies into the iframe, because /api/v3/auth/* is not reachable cross-origin from your page.
  • restoreSession() returns identity, not a credential — an endUserId and nothing more.
So there is no token for your app to store, forward, or accidentally leak. There is also nothing to pass to the Portal constructor after signing in: the same instance you configured is the one that becomes authenticated.
Client Auth requires @portal-hq/web 4.0.0 or later.

Prerequisites

Choose an authentication mode

The Web SDK accepts four credential modes. Configure exactly one — the SDK does not reject more than one, and resolves them in a fixed order: clientAuth, then apiKey, then authToken, then authUrl. The first three assume you already have a client and are authenticating it; see Web authentication methods. Use clientAuth when you want Portal to identify the user and create the client as part of the sign-in.

Configure Portal for Client Auth

Pass clientAuth instead of a credential. The iframe boots unauthenticated and waits for a sign-in.
isAccountAbstracted only takes effect on a user’s first sign-in. A returning user keeps the client they already have.
Resolve these values from your own backend rather than hardcoding them in client-side bundles. The Auth Environment ID is safe to treat as public — like an OAuth client ID — but the redirect and template values are configuration you will want to change per environment.

Handle the unauthenticated first state

Read this before writing any sign-in code. A Portal configured for Client Auth posts authenticationRequired during configuration and stops there — it does not become ready until a session is adopted. onAuthenticationRequired is replayed to late subscribers, so you cannot miss it by subscribing a moment too late. Three signals are available, and each answers a different question: onReady answers a question about the SDK, not about your user. Do not treat it as proof that someone is signed in — see the warning below. What a session begins is the result of completing a sign-in — completeOAuthLogin(), confirmMagicLink() or verifyTotp() — or of restoreSession(). Those return values are the authoritative signal that someone is now signed in, so keep the answer in one place your app owns:
Do not derive “signed in” from onReady. It is emitted at most once per page load — adopting a session posts a separate internal signal, and portal.auth.clearSession() deliberately leaves readiness unchanged — so an app that sets its signed-in flag from onReady gets stuck in a signed-out state on the second sign-in of the same page load. Set it from the result of a completed sign-in or of restoreSession() instead, as above.
Do not start a sign-in while a session is already live. A second sign-in mints a second session and can adopt a different end user on top of the current one. Offer your sign-in controls only while endUserId is null, and require a sign-out first.
Until a session is adopted the iframe never reaches ready, so a loading state that waits only for onReady never resolves. Gate wallet and API calls on onReady; gate your sign-in UI on onAuthenticationRequired.

Check which methods are enabled

autoCreateWallet is a signal for your app — nothing in the SDK or the API acts on it. Check for an existing wallet before creating one; a returning end user keeps the wallet they already have. See Create a wallet.
A two-factor requirement is not visible here. It only appears when a sign-in is completed, so your callback route must always be ready for it.

Start a sign-in

Google or Apple

getAuthorizeUrl() returns a provider URL for your app to navigate to. The sign-in completes later, on your callback route. Offer these controls only while nobody is signed in — see Handle the unauthenticated first state.
Navigate in the current tab, as above, rather than opening the URL in a new tab or window: a Google or Apple sign-in is bound to the tab that started it. See Google and Apple sign-ins are bound to this tab.
Fetch a fresh authorize URL for every attempt. A single backend response shares one single-use state across both providers, so caching a URL — or starting a Google sign-in and then an Apple one from the same response — invalidates the other.
The SDK also exports signInWithGoogle() and signInWithApple(), which run the sign-in in a popup. They cannot currently complete a Google or Apple sign-in: both providers serve their sign-in pages with Cross-Origin-Opener-Policy: same-origin, which switches the popup’s browsing context group and permanently severs window.opener, so the popup has no way to hand its callback URL back. Use the full-page redirect above.

Google and Apple sign-ins are bound to this tab

This binding requires @portal-hq/web 5.0.0 or later. Earlier versions don’t bind a sign-in to the tab that started it. If you serve or proxy the Portal iframe yourself, serve the 5.0.0 iframe.
Every getAuthorizeUrl() call binds the new sign-in to the current browser tab with PKCE. The Portal iframe creates a one-time secret and keeps it in its own storage for this tab, where your page can’t read it. It sends Portal only a hash of the secret when the sign-in starts, and the secret itself only when it completes the sign-in, so a callback can’t complete a sign-in that another browser started. You don’t pass or store anything yourself, and getAuthorizeUrl() returns a URL only once the secret is stored. This changes how sign-ins behave:
  • Finish in the tab that started it. The provider must return the user to your callback route in the same tab. Keep that route on the same site as the page that starts the sign-in, because browsers can keep the Portal iframe’s storage separately for each site. A callback that opens in another browser can’t complete, and one that opens in another tab generally can’t either.
  • One sign-in at a time. Each auth environment has one Google or Apple sign-in in progress per tab. Starting a new one replaces it, and a callback from the earlier attempt can no longer complete. A magic link is unaffected.
  • Finish within 15 minutes. The tab keeps a sign-in for 15 minutes after getAuthorizeUrl() returns, and a callback handled later can’t complete. Portal also gives the user 10 minutes to finish at Google or Apple. After that, the callback comes back with an error and parseRedirect() throws a ProviderRejectedError (see Grants are single use).
  • Signing out cancels it. clearSession() also cancels a sign-in in progress. See Sign out.
A Google or Apple callback carrying a grant that doesn’t belong to this tab’s sign-in in progress can’t complete, and fails in one of two ways:
  • If this tab has no Google or Apple sign-in in progress, completeOAuthLogin(), like the deprecated handleRedirect(), rejects with an error whose id is AuthErrorId.OAuthFlowNotStarted, and nothing is sent to Portal.
  • If this tab has a different sign-in in progress, for example because a new one replaced it, Portal refuses the callback’s grant. That error carries no id.
In either case, start a new sign-in. Other failures, including a callback that carries an error instead of a grant, are covered in Handle errors. sendMagicLink() resolves once Portal has handed the email off for delivery. It tells you nothing about the eventual sign-in, which arrives at your callback route when the user opens the link. Your callback completes it only after the user confirms the email address the link signs in to (see Confirm a magic link).
Lowercase and trim the address before you call sendMagicLink(). The API rejects a non-lowercase address with a 400, and the SDK passes what you give it through unchanged — so a plain text input breaks for any user who capitalizes.
Every call sends a real email, and sends are rate limited to 10 per address per minute. Never retry automatically; make a resend an explicit user action.

Build the callback route

handleRedirect() is deprecated and will be removed in the next major version. It completes a magic link in one step, without first showing the user the email address and waiting for them to confirm, which lets a user be signed in from a link they did not request. Use parseRedirect() and the methods below instead.
parseRedirect(), completeOAuthLogin(), getMagicLinkDetails(), confirmMagicLink(), AuthErrorId and TotpErrorId require @portal-hq/web 5.0.0 or later. Earlier versions complete every sign-in through handleRedirect(), which is now deprecated (see Migrate from handleRedirect()).
Add a route at the exact URL on your allow list. Every sign-in returns there, and completing it takes two steps:
  1. Read the callback URL with parseRedirect(). It runs locally and synchronously, sends nothing to the Portal iframe or to Portal, and tells you which kind of sign-in the URL completes.
  2. Complete it with the method for that kind:
    • Google or Apple (AuthMethod.Google, AuthMethod.Apple): call completeOAuthLogin(redirect.token).
    • Magic link (AuthMethod.EmailMagicLink): call getMagicLinkDetails(redirect.token), show the user the email, and call confirmMagicLink(redirect.token) only once they confirm it. See Confirm a magic link.
completeOAuthLogin() and confirmMagicLink() resolve with the same result: the signed-in identity, or a two-factor challenge (see Handle two-factor authentication). On success the iframe stores the session and adopts it before the result reaches your page. parseRedirect() returns a ParsedRedirect, with loginType and token, or null when the URL isn’t a Client Auth result for this page:
  • it doesn’t target clientAuth.redirectUrl, or carries no token,
  • it carries an unknown sign-in marker, or both login_type and authMethod, or
  • it is longer than 8192 characters.
A null lets the rest of your router handle the URL. parseRedirect() throws a ProviderRejectedError, whose id is AuthErrorId.ProviderRejected, only when a URL to your redirectUrl carries ?error=…: the provider sent the user back without completing the sign-in. It also throws when clientAuth.redirectUrl isn’t configured, since no URL can be matched. Because the page loads fresh, wait for the SDK before completing the sign-in — and subscribe to both onReady and onAuthenticationRequired. A Client Auth Portal does not become ready until a session is adopted, so on the usual fresh callback load only onAuthenticationRequired fires. If the route is instead reached with a session already live — client-side navigation, or a restoreSession() that resolved during startup — portal.ready is already true and onReady invokes your callback synchronously. Either can be the one that runs, so guard the work to a single run.
ParsedRedirect keeps the token out of JSON.stringify and string conversion, so logging a ParsedRedirect doesn’t leak the grant. Read redirect.token only to pass it to the SDK.
forgetCallbackUrl() changes the address bar with history.replaceState(). If your app uses a client-side router, put the redirect URL back through that router’s own replace navigation instead, such as router.replace(), so the router’s record of the current URL stays in step with the address bar.

Reloaded callbacks

A browser doesn’t deliver a callback twice to the page that handled it, but the user can reload the page or open the same link again. parseRedirect() and getMagicLinkDetails() don’t use up a grant, so calling them again sends nothing that changes the sign-in. Route every callback through exactly one handler in your app. The behavior below is a safety net, not something to rely on: once the page reloads or the session ends, handling the same callback again fails because its grant has already been spent. On load, restore the stored session instead of handling the callback again. Within one page load, completing the same sign-in twice doesn’t sign the user in twice. The Portal iframe handles completeOAuthLogin(), confirmMagicLink() and the deprecated handleRedirect() one call at a time, so a second call with the same token waits for the first:
  • If the first call succeeded, the second resolves to the same result without contacting Portal, as long as the session it created is still the current one and hasn’t ended. For a two-factor challenge, it gets the same challenge back while that step is still pending.
  • If the first call failed, the second is a new attempt and sends its own request. See the retries below.
Only the most recent successful sign-in is remembered, and only by the Portal iframe of the current page load. A call with the same token is no longer answered from memory once:
  • the session has ended, through clearSession() or Portal invalidating it,
  • another sign-in has completed in this page, or
  • the page has reloaded, or the call comes from another tab.
From then on the grant is treated as new, and it is already used: a magic link’s getMagicLinkDetails() and confirmMagicLink() reject with AuthErrorId.GrantRejected, and a Google or Apple callback fails with AuthErrorId.OAuthFlowNotStarted, or, if another Google or Apple sign-in has started in this tab since, with Portal’s 401, which carries no id. If the first call signed the user in, the session is still stored unless the user has signed out since, so restoreSession() finds it. That is why the example puts the address bar back to your redirect URL, without the grant, as soon as the sign-in completes or is cancelled. A reload after that finds no sign-in result, and the example says so. A failed completion is never remembered: the error reaches your page unchanged, and calling the same method again with the same token sends a new request. For Google or Apple, the sign-in in progress is kept. Whether Portal accepts the retry depends on the first attempt: Portal uses up a grant early while processing it, before it creates the session. A retry can succeed only if the first attempt failed before that point, typically because it never reached Portal. Otherwise the retry is refused: with AuthErrorId.GrantRejected for a magic link, and with Portal’s 401, which carries no id, for Google or Apple. Start a new sign-in. A magic link signs in whoever opens it, to the account it was sent for. Anyone can get a magic link for their own email address, for example by signing in to your app, and forward it to your user. If your callback completed every magic link as soon as it loaded, opening that link would sign your user in to the sender’s account, where they could, for example, fund a wallet the sender controls. Completing a magic link in two steps gives the user a chance to notice a link that isn’t theirs before anything is signed in. It is a safeguard, not a guarantee: it works only if your app shows the email address clearly and the user reads it. A callback that still completes magic links through the deprecated handleRedirect() skips it entirely. The two steps:
  1. getMagicLinkDetails(token) reads the email address the link signs in to, without using up the link. It resolves with { email }, the full address. Masking it, if you want to, is up to your app.
  2. confirmMagicLink(token) completes the sign-in. Call it only after the user confirms, on your own page, that the email address is theirs.
Portal doesn’t ship a confirmation screen. Show the email and two clear choices:
The callback route in Build the callback route renders it. A second click doesn’t sign the user in twice: the Portal iframe handles confirmations one at a time, and one that follows a successful confirmation resolves to the same result (see Reloaded callbacks). The route’s guard and the disabled buttons keep your page from running two confirmations at once. Cancelling uses up nothing, so the link stays valid until it expires. If confirming fails for any reason other than AuthErrorId.GrantRejected, the route keeps the confirmation on screen so the user can try again. The retry can succeed only if the failed attempt didn’t get as far as using up the link, typically because it never reached Portal, and otherwise rejects with AuthErrorId.GrantRejected. Other failures, such as a rate limit, a server error or a dropped connection, reach your page unchanged and carry no id. getMagicLinkDetails() is rate limited for each link, so don’t poll it: call it once per callback, and again only when the user asks. Both methods reject before sending anything when the token is empty.

Migrate from handleRedirect()

handleRedirect() is deprecated and will be removed in the next major version. It still works, and completes a Google or Apple callback exactly as completeOAuthLogin() does. For a magic link, though, it signs the user in at once, without the confirmation step, so the user gets no chance to notice a link that isn’t theirs. It logs a deprecation warning each time it does, when your logLevel shows warnings. It shares the remembered result with completeOAuthLogin() and confirmMagicLink(), but a magic link Portal refuses still rejects as it always has here: with Portal’s 401 error, which carries no id, rather than with AuthErrorId.GrantRejected. parseRedirect() is stricter than handleRedirect() in three cases that handleRedirect() keeps for compatibility:
  • Without clientAuth.redirectUrl, parseRedirect() throws, while handleRedirect() accepts a callback to any URL.
  • For a URL carrying both login_type and authMethod, parseRedirect() returns null, while handleRedirect() completes it as Google or Apple when login_type names one.
  • For a Google or Apple callback longer than 8192 characters, parseRedirect() returns null, while handleRedirect() still completes it.
Send every callback that parseRedirect() reads as a magic link to the confirmation step, never to handleRedirect().

Handle two-factor authentication

If your environment requires a second factor, a completed sign-in resolves with status: 'totpRequired' instead of a session. totpLink is an otpauth:// URI on a user’s first sign-in — render it as a QR code for their authenticator app — and null once they are enrolled.
Rendering the QR code is your app’s job; Portal does not ship a QR component. Any library works — qrcode.react is used above — and challenge.totpLink should be passed verbatim.
From @portal-hq/web 5.0.0, the TOTP step stays inside the Portal iframe, together with the token that authorizes it: challenge.userJwt is always absent, and verifyTotp() takes only the code. The step lives in the iframe’s memory, so it doesn’t survive a reload; after one, start a new sign-in. A failed verifyTotp() that Portal or the iframe refused carries one of these ids. Any other failure, such as a server error or a dropped connection, carries no id and usually leaves the step pending, so the user can submit a code again. A code Portal accepted spends the step even if the sign-in then can’t complete, for example when the iframe can’t save the session: the next call rejects with TotpErrorId.ChallengeNotFound.
verifyTotp(code, userJwt) from earlier versions still compiles, but the second argument is ignored, and passing a value logs a warning once when your logLevel shows warnings. Code that stores challenge.userJwt as a string no longer compiles: its type is now undefined.
For what the second factor is and how to reset an enrollment, see Two-factor authentication.

Restore the session

restoreSession() asks the iframe whether it still holds a stored session for this auth environment. The SDK never calls it for you. Its result is authoritative in the same way the redirect result is, so hand it to the same adopt path:
restoreSession() returns identity information — { endUserId } — and never a credential. The Client Session Token stays on the Portal origin. It is also not proof the session is still valid; validity is only discovered on the first authenticated call.

Sign out

This drops the in-memory token and deletes the stored copy for this auth environment, and the iframe returns to its unauthenticated state — so your onAuthenticationRequired handler fires again and clears the signed-in state you set with adopt. clearSession() also cancels a Google or Apple sign-in in progress in this tab: a callback for that sign-in that completeOAuthLogin() or handleRedirect() completes afterwards fails with AuthErrorId.OAuthFlowNotStarted. If your app clears the session as part of starting a sign-in, call it before getAuthorizeUrl(), not after. Calling it once the URL has returned abandons that sign-in, and also signs out any current session, so do that only on purpose. Don’t call it on your callback route before the callback has completed. If you call clearSession() while completeOAuthLogin(), confirmMagicLink() or handleRedirect() is still waiting for Portal, the Portal iframe finishes that completion first. It resolves as usual, and clearSession() then ends the session it created, so the user ends up signed out either way. Your onAuthenticationRequired handler fires after the completion’s result, so the pattern in Handle the unauthenticated first state ends signed out too.
There is no server-side revoke endpoint, so this is a local sign-out; the token stays valid until the backend expires it. clearSession() deliberately does not fire onSessionInvalidated — you already know about a sign-out you asked for. See API Keys for session lifetimes.
If you use Google Drive backups, starting in 5.0.0, clearSession() also ends the Google Drive session held by the Portal iframe, so the next backup or recovery asks the user to choose a Google account. See Google sign-in and sessions.
Signing out does not delete the wallet’s signing shares. The session lifecycle and the wallet lifecycle are separate: when the user signs in again, they continue with the same wallet, provided that wallet is otherwise still available to them.

Handle session invalidation

When the backend rejects the session with a 401, it ended somewhere your app cannot see and the user has to sign in again. The subscription belongs in SignedInUserProvider from Handle the unauthenticated first state, which is where the example above puts it.
Subscribe from an app-level component or provider that outlives your individual routes. Unlike onAuthenticationRequired, this event is not replayed to late subscribers, so if the only listener lives inside a route or tab that is unmounted when the session ends, the event is missed and your app carries on looking signed in.
onSessionInvalidated() does not cover every failure. It fires when a request that actually carried the session is rejected, but a failure inside an MPC operation may surface only as an error from that call. Handle errors from the call itself as well as subscribing here.
As with a sign-out, an invalidated session does not delete the wallet’s signing shares — only the credential is gone. Wallet state queries cannot be answered without a session, so treat them as unknown until the user signs in again rather than as evidence the wallet is missing.

Handle errors

Credential failures are normalized to PortalCredentialError. Branch on its reason.
Use PortalCredentialError.is(error), never instanceof. The type is identified by a cross-copy brand, so instanceof returns false when a dependency tree resolves two copies of the package — silently downgrading a real SessionInvalidated to an unhandled error.
A failed sign-in is not a PortalCredentialError. The failures you need to tell apart carry an id; compare it with AuthErrorId: Any other failure carries no id: a Google or Apple grant Portal refuses (a 401), including a callback for a sign-in this tab has since replaced; a magic link refused through handleRedirect(); a storage failure; a rate limit; a server error; or a dropped connection. Report it as a failed sign-in. For the failure cases every SDK shares, see When a sign-in fails.
Popup helpers throw PortalAuthPopupError, which you will not encounter using the redirect flow above.
The Web and React Native Client Auth APIs are not the same shape — different entry point, different sign-out, and a different restoreSession() return type. Do not port code between them; use each platform’s guide.

Next Steps

Now that your user is signed in, create a wallet and send tokens. For the dashboard and provider configuration behind this flow, see Authentication.