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

# Connect Session

> Generate connect session tokens from your backend so your end-users can link their accounts through the Hub.

A **connect session** is a short-lived token that authorizes one of your end-users to link an account. Your backend creates it with your [API key](/embed/api-keys), so the key is never exposed to the frontend.

<Note>
  **Prerequisites:** a StackOne [API key](/embed/api-keys), and a [connector profile](/gateway/quickstart#setup-connector-profile) enabled for the provider you're connecting.
</Note>

## Create a session

Call the [Connect Sessions endpoint](/platform/api-reference/connect-sessions/create-connect-session) from your backend. Two fields are **required**:

* **`origin_owner_id`**: your identifier for the customer's organization
* **`origin_owner_name`**: a human-readable name for that organization, stored against the account

<Warning>
  Always set `origin_owner_id` server-side. Never pass it through from a client-side request, or a customer could claim another customer's linked accounts.
</Warning>

<CodeGroup>
  ```typescript TypeScript SDK theme={null}
  import { StackOne } from "@stackone/stackone-client-ts";

  const stackOne = new StackOne({
    security: {
      username: process.env.STACKONE_API_KEY,
      password: "",
    },
  });

  app.post('/stackone_connect_sessions', async (req, res) => {
    const { originUsername, provider } = req.body;

    try {
      const result = await stackOne.connectSessions.createConnectSession({
        originOwnerId: "customer-123",
        originOwnerName: "Acme Inc",
        originUsername: originUsername,
        provider,
      });

      res.send({ token: result.connectSessionTokenAuthLink?.token });
    } catch (e) {
      res.status(500).send('error when trying to fetch session');
    }
  });
  ```

  ```python Python (HTTP) theme={null}
  from flask import Flask, request, jsonify
  import requests
  import base64

  app = Flask(__name__)

  @app.route('/stackone_connect_sessions', methods=['POST'])
  def stackone_connect_sessions():
      STACKONE_API_KEY = 'YOUR_STACKONE_API_KEY'
      headers = {
          'Authorization': 'Basic ' + base64.b64encode(f"{STACKONE_API_KEY}:".encode()).decode(),
          'Content-Type': 'application/json',
      }
      req_data = request.json

      payload = {
          'origin_owner_id': 'customer-123',
          'origin_owner_name': 'Acme Inc',
          'origin_username': req_data.get('originUsername'),
          'provider': req_data.get('provider'),
      }

      try:
          response = requests.post(
              'https://api.stackone.com/connect_sessions',
              headers=headers,
              json=payload
          )
          token = response.json().get('token')
          return jsonify({'token': token})
      except Exception as e:
          return ('error when trying to fetch session', 500)
  ```
</CodeGroup>

Return the token to your frontend, where the Hub consumes it to start [account linking](/embed/account-linking/overview).

## New or existing account

The `origin_owner_id` + `origin_owner_name` + `provider` combination decides whether a new account is created or an existing one is updated:

| Combination seen before?                  | Result                                          |
| ----------------------------------------- | ----------------------------------------------- |
| No                                        | New account created                             |
| Yes                                       | Existing account opened in edit mode            |
| — with `account_id`                       | That specific account opened in edit mode       |
| — with `multiple: true` (no `account_id`) | New account created regardless of existing ones |

Use `multiple: true` when one customer needs several separate accounts for the same provider. It has no effect when `account_id` is set.

To list a customer's linked accounts later, filter `GET /accounts` by `origin_owner_id` — see [Multi-Tenant Accounts](/features/multi-tenant-accounts).

## Target a specific connector profile

Passing `provider` alone uses the project's [default connector profile](/connect/managing-connectors/overview) for that provider, which is right for most cases. To route a session to a specific profile (multiple profiles per provider, or migrating users to a new connector version), pass its `connector_profile_id`. Get the ID from [`GET /connector_profiles`](/platform/api-reference/connector-profiles/list-connector-profiles):

```bash theme={null}
curl -X POST https://api.stackone.com/connect_sessions \
  -H "Authorization: Basic <base64(api_key:)>" \
  -H "Content-Type: application/json" \
  -d '{
    "origin_owner_id": "customer-123",
    "origin_owner_name": "Acme Inc",
    "provider": "bamboohr",
    "connector_profile_id": "01JHMM0V..."
  }'
```

The resulting account inherits that profile's connector version pin. The most common reason to target a profile this way is moving end users onto a new connector major version that requires them to reauthenticate. See [Migrating to a new version](/connector-building/connector-versioning#migrating-to-a-new-version) for that flow.

## Filtering connectors

Control which connectors appear in the Hub by configuring the connect session on your backend.

You can specify a `provider` or `categories` property when creating the connect session to control which connectors appear in the Hub:

* **`provider`**: Opens the Hub directly at the credential entry screen for a specific connector, bypassing the connector listing
* **`categories`**: Filters the Hub to show only connectors from specified categories (e.g., `hris`, `ats`)

If neither is specified, the Hub displays all connectors enabled for the project.

<Warning>
  The connector specified in `provider` must be enabled in the [Connector Profiles page](https://app.stackone.com/connector_profiles) of the associated project.
</Warning>

Retrieve valid `provider` keys from [`GET /actions`](/platform/api-reference/actions/list-all-connectors-actions-metadata). Each connector in the response carries a `key`, which is the value to pass here.

<CodeGroup>
  ```javascript JavaScript theme={null}
  // Skip connector list, go directly to BambooHR
  const result = await stackOne.connectSessions.createConnectSession({
    originOwnerId: "customer-123",
    originOwnerName: "Acme Inc",
    provider: "bamboohr",  // Go directly to this connector
  });
  ```

  ```javascript JavaScript (Categories) theme={null}
  // Show only HRIS connectors
  const result = await stackOne.connectSessions.createConnectSession({
    originOwnerId: "customer-123",
    originOwnerName: "Acme Inc",
    categories: ["hris"],  // Filter to HRIS category
  });
  ```
</CodeGroup>

## Next steps

<CardGroup cols={2}>
  <Card title="Account Linking" icon="link" href="/embed/account-linking/overview">
    Embed the Hub, or share an Auth Link, to consume the token you just created.
  </Card>

  <Card title="Handle Account Events" icon="webhook" href="/embed/handle-account-events">
    React to accounts being linked, updated, or disconnected.
  </Card>

  <Card title="Multi-Tenant Accounts" icon="users" href="/features/multi-tenant-accounts">
    Keep each customer's linked accounts separate with `origin_owner_id`.
  </Card>

  <Card title="Connect Sessions API" icon="code" href="/platform/api-reference/connect-sessions/create-connect-session">
    Every request field and response shape.
  </Card>
</CardGroup>
