# Onboarding mode

Source: https://docs.tradeit.app/sdk/onboarding

Start each user with the Trade It Portal in **Onboarding mode**. It explains your app’s access, handles sign-in, and connects their first brokerage without leaving your app.

After saving their tokens, use the same portal in [Connection mode](/sdk/connect) to add or reconnect brokerages.

![Your app’s access, security, privacy, and Continue button.](https://images.tradeit.app/docs/onboarding_info.png?v=2)
Review access

![Six code boxes, resend, and an option to correct the email address.](https://images.tradeit.app/docs/onboarding_otp.png?v=2)
Verify account

![Brokerage selection and the option to use connected accounts.](https://images.tradeit.app/docs/onboarding_connect.png?v=2)
Connect a brokerage

![Your backend creates an onboarding URL with an optional email hint. Your app opens the Trade It modal. The user reviews access and signs in. Your app receives an authorization event and sends the code to your backend. The modal opens brokerage connection.](/images/sdk/onboarding/flow.svg)

## Configure your client [#configure-your-client]

**Your backend** · One-time setup

[Create your organization and save its credentials](/sdk#_1-create-your-organization-and-get-credentials). Register a redirect URI on the website where you will open the portal, then set these server environment variables:

```dotenv
TRADE_IT_CLIENT_ID=your_client_id
TRADE_IT_CLIENT_SECRET=your_client_secret
TRADE_IT_REDIRECT_URI=https://app.example.com/auth/tradeit/callback
```

> **Match your website’s origin**
>
> The `redirect_uri` must use the same scheme, hostname, and port as the website opening the portal. Register a separate URI for each test or production origin. Use HTTPS in production; HTTP localhost is supported for development. The portal sends its authorization event to this origin without navigating to the URI.

## Create Portal URL [#create-portal-url]

**Your backend** · `POST https://api.tradeit.app/api/portal`

Use your Client ID and Client Secret from step 1 with Basic authentication. Put authorization settings in `oauth_options` and optional brokerage settings in `connect_options`.

```js
import { randomBytes, createHash } from 'node:crypto';

// Bind this attempt to your user and protect the code exchange with PKCE.
const state = randomBytes(32).toString('base64url');
const verifier = randomBytes(32).toString('base64url');
const credential = Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64');

// Create the portal URL for this user.
const portal = await fetch('https://api.tradeit.app/api/portal', {
  method: 'POST',
  headers: { Authorization: `Basic ${credential}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    oauth_options: {
      redirect_uri: redirectUri,
      state,
      code_challenge: createHash('sha256').update(verifier).digest('base64url'),
      email_hint: user.email, // Optional. Omit to show all sign-in options.
      name: user.name,       // Optional. Personalizes the experience.
    },

    connect_options: {}, // Optional. Customizes brokerage selection.
  }),
}).then(res => res.json());
```

Pass `portal.url` to your frontend. Retain the state, verifier, issuer, token endpoint, and expiry on your server for this user’s authorization attempt. Keep the Client Secret on your server.

> **Portal URL lifetime**
>
> The URL expires after **30 minutes**. Keep the returned `issuer` and `tokenEndpoint` on your server for step 4.

### Request details [#request-details]

- **`oauth_options`** · `object` · required

Required with Basic authentication to create an onboarding portal. The client ID comes from your credentials.

- **`oauth_options.redirect_uri`** · `string` · required

Your exact registered redirect URI, on the same origin as the website opening the portal. The portal sends an authorization event without navigating to this URI.

- **`oauth_options.state`** · `string` · required

A cryptographically random value binding this attempt to your signed-in user. Save it on your server and validate the returned state before exchanging the code.

- **`oauth_options.code_challenge`** · `string` · required

Base64url-encoded SHA-256 hash of your PKCE verifier (S256). Keep the verifier on your server for the code exchange.

- **`oauth_options.email_hint`** · `string`

Start with a one-time email code instead of the full sign-in choices. Users can switch methods or correct the address.

- **`oauth_options.skip_verification`** · `boolean`

Use with `email_hint` only when your platform has already verified that email belongs to the user. New Trade It users can skip the sign-up verification step; existing users must still sign in. Consent and connection steps are unchanged.

- **`oauth_options.name`** · `string`

The user’s name, used to personalize onboarding.

- **`connect_options`** · `object`

Customize brokerage selection. Omit this object or send `{}` to show every active brokerage. Use either `brokerage_code` or `brokerage_filter`, never both.

- **`connect_options.brokerage_code`** · `string`

Skip the picker and open this brokerage’s connection flow directly. See [supported brokerages](/brokerages). Cannot be combined with `brokerage_filter`.

Allowed values: `robinhood`, `coinbase`, `etrade`, `moomoo`, `kraken`, `fidelity`, `charles_schwab`, `webull`, `tradestation`, `tradestation_paper`, `public`, `tastytrade`.

- **`connect_options.brokerage_filter`** · `object`

Filter the brokerage picker by capabilities or brokerage codes. Inactive brokerages are omitted. If nothing matches, the picker shows every active brokerage. Filters do not change your app’s permissions.

- **`connect_options.brokerage_filter.supports`** · `string[]`

Only show brokerages supporting every listed capability.

Allowed values: `stock`, `crypto`, `options`, `fractional-shares`, `notional-orders`, `take-profit`, `stop-loss`.

- **`connect_options.brokerage_filter.include`** · `string[]`

Only show these brokerage codes. See [supported brokerages](/brokerages).

Allowed values: `robinhood`, `coinbase`, `etrade`, `moomoo`, `kraken`, `fidelity`, `charles_schwab`, `webull`, `tradestation`, `tradestation_paper`, `public`, `tastytrade`.

- **`connect_options.brokerage_filter.exclude`** · `string[]`

Hide these brokerage codes. Exclusions take precedence over `include`.

Allowed values: `robinhood`, `coinbase`, `etrade`, `moomoo`, `kraken`, `fidelity`, `charles_schwab`, `webull`, `tradestation`, `tradestation_paper`, `public`, `tastytrade`.

#### Sign-in options [#sign-in-options]

> **Choose the first sign-in screen**
>
> Supply `oauth_options.email_hint` to start with a one-time email code. Omit it to show all social and email sign-in options. Users can switch methods or correct their address in the portal.

```json
{
  "oauth_options": {
    "redirect_uri": "https://app.example.com/auth/tradeit/callback",
    "state": "your_random_state",
    "code_challenge": "your_pkce_challenge",
    "email_hint": "john@test.com",
    "name": "John Smith"
  }
}
```

![Email verification screen with six code boxes, resend, and other sign-in options.](https://images.tradeit.app/docs/onboarding_otp.png?v=2)
With email_hint · Email code

![Sign-in choices for Google, Apple, X, Discord, and email.](https://images.tradeit.app/docs/onboarding_social_sign_in.png?v=3)
Without email_hint · Sign-in choices

> **Bypassing verification for new users**
>
> Set `oauth_options.skip_verification` to `true` together with `oauth_options.email_hint` to assert that your platform has already verified the user’s identity and that the supplied email belongs to them. For new Trade It users, the portal can proceed directly from consent to brokerage connection without sending an email or OTP. Existing Trade It users must still sign in.

#### Connection options [#connection-options]

Choose which brokerages users can choose from. These settings have the same behavior as the [Connection mode options](/sdk/connect#request-fields).

##### Full list [#full-list]

Omit `connect_options`, or pass an empty object, to show every active brokerage:

```json
{
  "connect_options": {}
}
```

![Full list of active brokerages and the option to use connected accounts.](https://images.tradeit.app/docs/onboarding_connect.png?v=2)

##### Filtered list [#filtered-list]

Use `brokerage_filter` to filter by capabilities (`supports`) or brokerage codes (`include` and `exclude`). For example, show options-supporting brokerages except Tastytrade:

```json
{
  "connect_options": {
    "brokerage_filter": {
      "supports": ["options"],
      "exclude": ["tastytrade"]
    }
  }
}
```

> **Brokerage filter behavior**
>
> The picker omits inactive brokerages. If nothing matches, it shows every active brokerage. Filters customize the picker; they do not change the access your app requests.

![Brokerage picker showing a filtered list of brokerages.](https://images.tradeit.app/docs/onboarding_connect_exclude.png?v=1)

##### One targeted brokerage [#one-targeted-brokerage]

Use `brokerage_code` to skip the picker and open one brokerage’s connection flow directly. Choose a code from the [brokerage list](/brokerages):

```json
{
  "connect_options": {
    "brokerage_code": "charles_schwab"
  }
}
```

Use either `brokerage_code` or `brokerage_filter` in a request, not both.

![Connection flow opened directly for Charles Schwab.](https://images.tradeit.app/docs/onboarding_connect_schwab.png?v=1)

## Open the portal [#open-the-portal]

**Your frontend** · `npm install @trade-it/react`

Open the portal on your front end. After the user consents to share data and signs in, their OAuth authorization code is emitted by the modal as an event.

Use `onAuthorization` to forward this code to your backend and exchange it for the user's access & refresh tokens.

```tsx
import { TradeItModal, useTradeIt } from '@trade-it/react';

function ConnectBrokerageButton() {
  const tradeIt = useTradeIt({
    // Save access on your server while the modal opens brokerage selection.
    onAuthorization: async authorization => {
      const saved = await fetch('/api/tradeit/complete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(authorization),
      });
      if (!saved.ok) throw new Error('Could not save access');
    },
  });

  async function connect() {
    const response = await fetch('/api/tradeit/portal', { method: 'POST' });
    if (!response.ok) throw new Error('Could not start onboarding');
    const { url } = await response.json();

    tradeIt.openConnect({ launch: { mode: 'connect', url } });
  }

  return (
    <>
      <button onClick={connect}>Connect my brokerage</button>
      {tradeIt.modalProps && <TradeItModal {...tradeIt.modalProps} />}
    </>
  );
}
```

> **Authorization events instead of redirects**
>
> In Onboarding mode, the portal sends the authorization code through `onAuthorization` instead of opening `redirect_uri`, so the modal can continue straight to brokerage connection. See [OAuth 2.0 Best Current Practices](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.17) for more info on this approach. Your registered `redirect_uri` still determines the receiving website’s origin and is used when exchanging the code for tokens.

## Save tokens [#save-tokens]

**Your backend** · `POST /api/tradeit/complete`

Use the token endpoint returned in step 2, the same PKCE `verifier`, and the registered `redirectUri`. `authorization` is the event received by `onAuthorization`.

```js
const tokens = await fetch(tokenEndpoint, {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credential}`,
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: authorization.code,
    code_verifier: verifier,
    redirect_uri: redirectUri,
  }),
}).then(res => res.json());
```

> **Bind tokens to the correct user**
>
> Before exchanging, validate the event’s state and issuer against the attempt saved for your signed-in user, and consume that attempt once. Protect your endpoints with authentication and CSRF checks. Save `tokens` securely for that user, then resolve `onAuthorization`; keep codes and tokens out of logs.

> **Token Expired?**
>
> Refresh access with the saved `tokenEndpoint` using the [refresh-token flow](/sdk/authentication#refresh-expired-tokens-server-side).

> **Adding another brokerage?**
>
> Use the [portal in Connection mode](/sdk/connect) with the user’s saved OAuth access token. Call the same `POST /api/portal` endpoint with Bearer authentication and omit `oauth_options`. There’s no need to repeat onboarding while your app’s authorization is valid.
