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

# Create a Finch Connect Session

> Set up Finch Connect to collect consent from your customers and begin syncing data from their HR or payroll system.

[Finch Connect](/how-finch-works/finch-connect) is the interface your customers will use to provide consent, approve permissions, connect their HR or payroll system, and authenticate. Finch will walk each employer through the appropriate flow based on the provider and [auth method](/implementation-guide/Integration-Preparation/Configure-Auth-Methods).  Finch Connect is supported via our [Frontend SDKs](/developer-resources/SDKs) for Javascript and React.

You can [embed Finch Connect](/implementation-guide/Connect/Set-Up-Finch-Connect#embedded-flow) into your application, or set up a [redirect flow](/implementation-guide/Connect/Set-Up-Finch-Connect#redirect-flow).

<Note>
  {" "}

  This section requires that you have created a Finch application and have access to a client\_id and client\_secret by completing
  the [Create a Finch Developer Account](implementation-guide/Connect/Create-Account)
  section.{" "}
</Note>

## Session Configuration

Every flow requires you to create a Finch Connect session with your `client_id` and `client_secret` and is configurable with the following parameters:

| Parameter                 | Required              | Description                                                                                                                                                                                                                                                                                                           |
| ------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `customer_id`             | true                  | A unique identifier for your customer.                                                                                                                                                                                                                                                                                |
| `customer_name`           | true                  | The name of your customer.                                                                                                                                                                                                                                                                                            |
| `customer_email`          | false                 | The email associated to your customer.                                                                                                                                                                                                                                                                                |
| `products`                | true                  | A space-separated list of permissions your application is requesting access to. See [Product Permissions](/api-reference/development-guides/Permissions) for a list of valid permissions. Please note that SSN is its own product scope.                                                                              |
| `redirect_uri`            | redirect only         | The URI your user is redirected to after successfully granting your application access to their system. This value must match one of your application's configured [redirect URIs](/implementation-guide/Connect/Create-Account#redirect-uris).                                                                       |
| `integration.provider`    | optional              | An optional parameter that allows you to bypass the provider selection screen by providing a valid `provider_id` from our list of [Providers](/integrations/providers).                                                                                                                                               |
| `integration.auth_method` | optional              | An optional parameter that allows you to bypass the provider selection screen by providing a valid `auth_method` for a provider from our list of [Providers](/integrations/providers).                                                                                                                                |
| `sandbox`                 | false                 | An optional value that allows users to switch on sandbox mode to connect to test environments. Allowed values: `finch` and `provider`. For more information, read our [testing guide](/implementation-guide/Test/Finch-Sandbox).                                                                                      |
| `manual`                  | false                 | An optional value which when set to true displays both [Automated and Assisted Providers](/integrations/integration-types) on the selection screen.                                                                                                                                                                   |
| `minutes_to_expire`       | false                 | An optional value which allows you to set the number of minutes the connect session should be valid for. Defaults to 30 days.                                                                                                                                                                                         |
| `connection_id`           | reauthentication only | A unique identifier created when an employer successfully authenticates through Finch Connect. This ID is only used for reauthentication. You will not have a `connection_id` for the first call. For all reauthentication flows you should include the `connection_id` to avoid duplicate connections being created. |

## Create a Connect Session

Using the configuration params described in the above sections, your **backend application** will make a call to [Create a New Connect Session](/api-reference/connect/new-session) `POST /connect/sessions`. When creating the connect session, include your internal customer\_id for your customer, the customer’s name and any of the optional fields listed below.

```js theme={null}
import Finch from '@tryfinch/finch-api';

const client = new Finch({
  clientId: 'My Client ID',
  clientSecret: 'My Client Secret',
});

async function main() {
  const createConnectSessionResponse = await finch.connect.sessions.new({
	  products: ["company", "directory", "individual", "employment", "payment", "pay_statement"],
	  customer_id: customer.id, // Your internal customer ID
	  customer_name: customer.name, // Your customer's name
	  customer_email: customer.email, // The email associated to your customer (optional)
	  integration: { // (optional)
			  provider: 'adp_run', // The provider you wand to show up in connect (optional)
			  auth_method: 'credential' // The auth method of the provider to show up (optional)
	  },
	  minutes_to_expire: 43200, // How long you want the session to last for (defaults to 30 days)
	  redirect_uri: '' // The URI to redirect to for the redirect connect flow (optional)
	  sandbox: false // create a sandbox session for a sandbox app (optional)
	  manual: false // A value that, when set to true, displays both Automated and Assisted providers on the selection screen (optional)
  });

	/**
	 * {
	 *   "session_id": "<A unique session ID that can be used with embedded connect>",
   *   "connect_url": "<The url of the connect session for the redirect flow>"
   * }
	**/
  console.log(createConnectSessionResponse);
}

main();
```

If your customer has successfully authenticated (completed Finch Connect and you see a Live connection on your dashboard) and you call `POST /connect/sessions` using the same `customer_id` you passed in, Finch will prompt you to re-authenticate instead and return the following error:

```
{
    "code": 400,
    "finch_code": "connection_already_exists",
    "message": "There's an existing connection for the customer_id: <session.customer_id>. Please use the /connect/sessions/reauthenticate endpoint instead.",
    "name": "bad_request",
    "context": {
      "customer_id": "<session.customer_id>",
      "connection_id": "<connection.id>"
    },
  }
```

If your customer has not yet successfully authenticated and you call `POST / connect/sessions` using the same `customer_id` you passed in, Finch will simply refresh the connect session and return the same `session_id`. You can do this if you wish to update the Customer Name or any other parameter before your customer connects. If you wish to update any parameters after the customer has connected, you will need to use `POST / connect/sessions/reauthenticate`.

### Best Practices: Creating Sessions

#### DO

* Always pass in a **stable and unique** `customer_id` for a given employer, and **reuse the same `customer_id` across retries or drop-offs.** Even if an employer opens the Connect session multiple times before successfully connecting, using the same `customer_id` ensures all attempts are tracked as a single staged session.
* If you think an employer intends to connect multiple entities or payroll systems, you can append an identifier to the `customer_id` to differentiate the Connect sessions (e.g.: `acme-1`, `acme-2`). Visit this [Help Center article](https://support.tryfinch.com/hc/en-us/articles/31148519242772-FAQs-Connection-ID-Session-ID) for more details.

#### DON'T

* Avoid generating new `customer_ids` on retries or failed connection attempts - this results in multiple redundant staged connections and could result in unintended behavior:
  * If an employer converts using Session\_Link\_1, Session\_Link\_2 will eventually expire
  * If an employer converts using both Session\_Link\_1 and Session\_Link\_2, they will inadvertently create two connections.

### Reauthentication Sessions

Your application should be able to generate a Finch Connect session for reathentication. This will avoid creating duplicate connections and ensure that the user is able to reauthenticate successfully to continue syncing data.

If a connection goes into a status of `reauth`, you will need to create a reauthentication session. This is done by calling [Create a new Connect session for reauthentication](/api-reference/connect/reauthenticate-session) (`POST /connect/sessions/reauthenticate`) endpoint with the `connection_id` of the connection that requires reauthentication. The response will include a new `session_id` and `connect_url` for the reauthentication session.

## Launch Finch Connect

Finch provides two options to launch Finch Connect: redirect and embedded. For both options, your customer will go through the same authentication flow in Finch Connect.

When launching either flow, you may optionally pass a state parameter. Finch Connect sessions are created server-side using your client credentials, so they are not vulnerable to the CSRF attacks that `state` is traditionally used to prevent. The `state` parameter is not required, but you may use it to carry context through the authorization code exchange or for additional security requirements specific to your application.

**Note that `state` is not a parameter accepted by `POST /connect/sessions` and will be silently ignored if passed — see the redirect and embedded flow sections below for how to include it in each flow.**

### Redirect Flow

Use the redirect flow if you are not using the Finch Frontend SDK or need to share a link directly with your customer, such as via email or a URL redirect.

1. **Configure Finch Connect** — Create a connect session using `POST /connect/sessions`. See [Create a Connect Session](#create-a-connect-session) above for details.
2. **Share Finch Connect** — Provide your customer with a link or button pointing to the `connect_url`. Your customer clicks it to redirect their browser to Finch Connect, hosted by Finch at `https://connect.tryfinch.com`, and initiate the authorization flow.
3. **Request access** — Finch Connect prompts your customer to approve the permissions your application is requesting and provide the credentials or information needed to connect their employment system.
4. **Retrieve the authorization code** — After your customer authenticates and grants access, Finch Connect redirects their browser to your `redirect_uri` with a short-lived authorization `code`.
5. **Exchange the code for an access token** — Your application exchanges the short-lived `code` for a long-lived `access_token`. See [Retrieve An Access Token](/implementation-guide/Connect/Retrieve-Access-Token) for details. The `access_token` is then used to make Finch API calls.

The `connect_url` supports an optional `state` parameter, which will be returned as-is to your `redirect_uri` after your customer authenticates. To use it, append it to the URL:

```
https://connect.tryfinch.com/authorize?session=<session_id>&state=foo
```

Finch Connect sessions are created server-side using your client credentials, so they are not vulnerable to the CSRF attacks that state is traditionally used to prevent. The state parameter is not required, but you may use it to carry context through the authorization code exchange or for additional security purposes specific to your application.

### Embedded Flow

Use the embedded flow if you are integrating via the Finch Frontend SDK and want your customer to complete the authorization flow within your application.

1. **Configure Finch Connect** — Create a connect session using `POST /connect/sessions`. See [Create a Connect Session](#create-a-connect-session) above for details.
2. **Share Finch Connect** — Provide your customer with a button that calls `connect.open()` with the `session_id`. Your customer clicks it to launch the Connect modal within your application and initiate the authorization flow.
3. **Request access** — Finch Connect prompts your customer to approve the permissions your application is requesting and provide the credentials or information needed to connect their employment system.
4. **Retrieve the authorization code** — Your application receives a short-lived authorization `code` via the SDK's `onSuccess` callback after your customer successfully authenticates.
5. **Exchange the code for an access token** — Your application exchanges the short-lived `code` for a long-lived `access_token`. See [Retrieve An Access Token](/implementation-guide/Connect/Retrieve-Access-Token) for details. The `access_token` is then used to make Finch API calls.

The `open` call accepts an optional `state` parameter if you need to carry context through the authorization flow:

```js theme={null}
connect.open({ sessionId, state });
```

We offer both a JavaScript and React frontend SDK, both of which can be viewed at the repository below. See the README in the repository for installation and usage instructions.

<CardGroup cols={1}>
  <Card title="Finch Connect SDK" icon="toolbox" iconType="duotone" color="#7A84FF" href="https://github.com/Finch-API/finch-connect-sdk" />
</CardGroup>

***

## Checkpoint + Next Step

<Check>
  After completing this step, you will have successfully integrated Finch
  Connect into your application's front end. This will enable users to
  authenticate with their employment systems, providing your application with
  the necessary authorization to [Retrieve An Access
  Token](/implementation-guide/Connect/Retrieve-Access-Token) in the next
  section.
</Check>

## Learn more

* [Finch Connect Best Practices](/implementation-guide/Deploy-and-Manage/Increase-Employer-Adoption)
