> For the complete documentation index, see [llms.txt](https://docs.sentiance.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sentiance.com/getting-started/sdk-integration/4.-user-creation.md).

# 4. User Creation

Please checkout  [SDK and User Management](/sdk/appendix/user-deletion.md) to understand what a Sentiance user is and how the SDK manages users and devices.

## Steps

{% stepper %}
{% step %}

### Prerequisites

As part of user creation, you will need the following:

1. **Sentiance API Key**\
   A valid Sentiance API key with the <mark style="color:$success;">**`user_link`**</mark> permission. Refer to the [API key creation guide](/getting-started/insights-control-tower/developer-dashboard/api-keys.md) to generate a key and give it the correct permission.
2. **User Creation Endpoint**\
   An API endpoint on your backend that accepts user creation requests from your app, and forwards them to Sentiance. It should use the Sentiance API Key for authentication.
   {% endstep %}

{% step %}

### Request an Authentication Code

1. From your app, send a user creation request to your own backend.
2. Forward this request to Sentiance by making an HTTP POST request to obtain an **authentication code**. The request must include a unique app-user identifier. Sentiance’s default (Europe) API endpoint is <mark style="color:$success;">**`https://api.sentiance.com`**</mark>. If you have specific regional requirements, contact Sentiance.

```http
POST /users/auth-code

Content-Type: application/json
Authorization: Bearer <sentiance-api-key>

{
    external_id: <unique-app-user-identifier>
}
```

3. The Sentiance API will respond with a json object containing an <mark style="color:$success;">**`authentication_code`**</mark>. This code is **valid for 10 minutes**. Forward it to your app, and use it to create a Sentiance user.

Here are code samples in Express (Nodejs) and Flask (Python) for handling user creation requests on your backend.

<details>

<summary>Complete Nodejs (Express) endpoint code sample</summary>

```javascript
const USER_LINK_API_KEY = "ABCDEF123456789...."; 
const authUrl = "https://api.sentiance.com/users/auth-code";

app.post("/sentiance-user-create", await (req,res) =>{
// validate the request and identify the user
  const externalID = "user_001";  // Identifier for this particular user: (email, phone number, userID)
  try {
      const sentianceRsponse = await fetch(authURL, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${USER_LINK_API_KEY}`,
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: JSON.stringify({
          external_id: externalID
        })
      });
    
      // validate the response to the sentiance platform
      const data = await sentianceRsponse.json();
      res.send(data["authentication_code");
  } catch (error) {
    console.error("Error getting auth code:", error);
      // respond with 4xx
  }
});


```

</details>

<details>

<summary>Complete Python (Flask) endpoint code sample</summary>

```python
import requests
from flask import Blueprint, jsonify, current_app
​
auth_bp = Blueprint("auth_bp", __name__)
​
@auth_bp.route("/get-auth-code", methods=["GET"])
def get_auth_code():
​
    ## DONT PUT YOUR API KEY ON YOUR APP -- SAMPLE ONLY
    USER_LINK_API_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    EXTERNAL_ID = "customer_id_001"
    sentiance_url = "https://api.sentiance.com/users/auth-code"
​
​
    ## Where api_key is the USER_LINK API Key you generated in ICT
    headers = {
        "Authorization": f"Bearer {USER_LINK_API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
​
    ## Where EXTERNAL_ID is user identifier you choose to assign
    ## (e.g., email address, userID, etc.).
    payload = {
        "external_id": EXTERNAL_ID
    }
​
    ## Send the "POST" request to Sentiance URL
    response = requests.post(
        sentiance_url,
        headers=headers,
        json=payload
    )
    return response.json()

```

</details>

#### UserCreation Data Flow

<figure><img src="/files/2h7Q5wMjB02dMwVmDAIm" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Create a User

Create a user by calling the SDK's <mark style="color:$success;">**`createUser()`**</mark> method, and passing it the authentication code that you received from Sentiance.

{% tabs %}
{% tab title="iOS" %}

```swift
import SENTSDK

let options = SENTUserCreationOptions(authenticationCode: authCode)
Sentiance.shared.createUser(options: options) { result, error in
    guard let result = result else {
        NSLog("User creation failed with reason \(error!.failureReason)")
        return
    }
    NSLog("Created a user with ID: \(result.userInfo.userId)")
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
import com.sentiance.sdk.Sentiance
import com.sentiance.sdk.usercreation.UserCreationOptions

val options = UserCreationOptions.Builder(authenticationCode).build()
Sentiance.getInstance(context).createUser(options).addOnCompleteListener { operation ->
    if (operation.isSuccessful) {
        val userInfo = operation.result.userInfo
        Log.d(TAG, "Created a user with ID: ${userInfo.userId}")
    } else {
        val error = operation.error
        Log.e(TAG, "User creation failed with reason ${error.reason.name}. Details: ${error.details}")
    }
}
```

{% endtab %}

{% tab title="React Native" %}

```typescript
import SentianceCore from '@sentiance-react-native/core';

async function createUser(authenticationCode: string) {
  try {
    const result = await SentianceCore.createUser({ authCode: authenticationCode })
    console.log(`Created a user with ID: ${result.userInfo.userId}`);
  } catch (e) {
    console.log(`User creation failed with error: ${e}`);
  }
}
```

{% endtab %}

{% tab title="Flutter " %}

```dart
import 'package:sentiance_core/sentiance_core.dart';

final sentiance = SentianceCore();

Future createUser(String authCode) {
  try{
    final result = await sentiance.createUser(CreateUserOptions(authCode: authCode));
    // check the returned CreateUserResult
    print("Created a user with ID: ${result.userInfo.userId}")
    
  } catch (e){ 
    // perform action on failed user creation 
    print("User creation failed with error: ${e}");
  }
}
```

{% endtab %}
{% endtabs %}

#### Specifying a Sentiance API Endpoint

If your Sentiance account is not located in the default Europe region, you must specify the corresponding Sentiance API endpoint when creating a user. Here's an example.

{% tabs %}
{% tab title="iOS" %}

```swift
let userCreationOptions = SENTUserCreationOptions(authenticationCode: authCode)
userCreationOptions.platformUrl = "https://api.p15.sentiance.com"
```

{% endtab %}

{% tab title="Android" %}

```kotlin
val createOptions = UserCreationOptions.Builder(authCode)
    .setPlatformUrl("https://api.p15.sentiance.com")
    .build()
```

{% endtab %}

{% tab title="React Native" %}

```typescript
await SentianceCore.createUser({ 
    platformUrl: "https://api.p15.sentiance.com", 
    authCode 
})
```

{% endtab %}

{% tab title="Flutter" %}

```dart
await sentiance.createUser(
    CreateUserOptions(
      authCode: authCode,
      platformUrl: "https://api.p15.sentiance.com",
    ),
);
```

{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Next: Enabling Detections

After having successfully created a Sentiance user, you can proceed to enable SDK detections. To do so, follow the instructions on [this page](/getting-started/sdk-integration/5.-enabling-detections.md).
{% endstep %}
{% endstepper %}
