# Sessions


Sessions allow distribution partners to establish consumer context for the ordering experience. Your platform provides user information to Gett, enabling a seamless experience with pre-filled details.

## How It Works

1. User authenticates on your platform (your own auth system)
2. Your backend creates a Gett session with user information via the Gett API
3. You initialize the Marketfront SDK with the session token
4. User enjoys a seamless ordering experience with their information pre-filled

<Mermaid chart={`sequenceDiagram
    participant User
    participant Partner as Your Platform
    participant API as Gett API
    participant Embed as Gett Marketfront

    User->>Partner: Logs in to your platform
    Partner->>API: POST /v1/marketfront/session/create
    Note over API: Validate API key<br/>Create session with user context
    API-->>Partner: session_token
    Partner->>Embed: Initialize with session_token
    Embed->>User: Ready for ordering`} />

---

## How the SDK Manages Sign-in

The SDK manages authentication progressively. Pass whatever user context you have at session creation — even an empty body produces a valid session suitable for anonymous browse. When the user reaches a checkout action, the embed prompts for sign-in inside its own UI; no host-page sign-in trigger is required, and you do not call any sign-in or upgrade endpoint yourself.

If you already have the user's identity at session-creation time, supply it via the request body below and the SDK skips the in-embed sign-in step.

---

## Session Creation

### Endpoint

| | |
|-------------|-----|
| Endpoint | `https://api.gett-tech.com/v1/marketfront/session/create` |
| Environment | Selected by your API key (Live or Sandbox) |

```http
POST /v1/marketfront/session/create
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

Authenticated with your partner API key (server-to-server only — never call this from a browser).

### Request Body

```json
{
  "partnerUserId": "user_12345",
  "email": "jane@example.com",
  "firstName": "Jane",
  "lastName": "Doe",
  "phone": "+15551234567",
  "address": {
    "address1": "123 Main St",
    "address2": "Apt 4B",
    "city": "Seattle",
    "state": "WA",
    "postalCode": "98101"
  }
}
```

Every field is optional. An empty body is valid — it produces an anonymous session, and the embed prompts the user to sign in when they reach checkout.

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `partnerUserId` | string | No | Stable user identifier in your system. Server mints a `gen_<guid>` if omitted. |
| `email` | string | Required when `firstName` or `lastName` is present | User's email address. |
| `firstName` | string | Required when `email` or `lastName` is present | User's first name. |
| `lastName` | string | Required when `email` or `firstName` is present | User's last name. |
| `phone` | string | No | E.164 format (e.g., `+15551234567`). Must be SMS-capable for order notifications. |
| `address` | object | No | Default delivery address — powers initial store discovery. See [`address`](#address-object) below. |

The `email` / `firstName` / `lastName` triple is all-or-nothing: supplying any one without the others returns `400 LEVEL_1_INCOMPLETE`. Supply all three to resolve a Gett user up front, or omit all three to keep the session anonymous (the embed will prompt for sign-in at checkout).

#### `address` object

```json
{
  "address1": "123 Main St",
  "address2": "Apt 4B",
  "city": "Seattle",
  "state": "WA",
  "postalCode": "98101"
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `address1` | string | Yes | Street address. |
| `address2` | string | No | Apartment, suite, unit, etc. |
| `city` | string | Yes | City. |
| `state` | string | Yes | Region or state. |
| `postalCode` | string | Yes | Postal code. |

### Response

```json
{
  "token": "gett_sess_abc123xyz",
  "expiresAt": "2025-01-15T12:00:00Z",
  "partnerUserId": "user_12345"
}
```

| Field | Type | Description |
|-------|------|-------------|
| `token` | string | Session token. Pass to the Marketfront SDK to establish consumer context. |
| `expiresAt` | string | ISO 8601 expiration timestamp. |
| `partnerUserId` | string | Echoes the caller-supplied `partnerUserId`, or the server-minted `gen_<guid>` when none was supplied. Store this to correlate sessions across token refreshes. |

## Using the Session Token

Initialize the Marketfront SDK with the session token returned from session creation. The session token encodes your partner identity, so no separate Partner ID is needed.

### Vanilla TypeScript

```typescript
import '@gett-co/marketfront';

// Your backend creates the session with user data
const { token } = await yourBackend.createGettSession(user);

const el = document.createElement('gett-marketfront');
el.sessionToken = token;
document.getElementById('container')!.appendChild(el);
```

### React

```tsx
import '@gett-co/marketfront';

function OrderPage({ sessionToken }: { sessionToken: string }) {
  return (
    <gett-marketfront
      session-token={sessionToken}
      onOrderComplete={(order) => console.log('Order:', order.id)}
    />
  );
}
```

---

## Session Lifecycle

### Expiration

Sessions expire 7 days after creation. The exact expiry is in the response's `expiresAt` field. Token lifetime is set by Gett and is not negotiable per request. Before expiration, create a new session:

```bash
POST https://api.gett-tech.com/v1/marketfront/session/create
```

The new session will inherit any in-progress cart from the previous session for the same `partnerUserId`.

To end a session early (e.g., on user logout), discard the token client-side. Calls made with a discarded token will continue to authorize until its natural expiry, so don't rely on discard alone to terminate a session.

---

## Security

### API Key Protection

Your API key authenticates session creation requests. Never expose it in client-side code.

```typescript
// Never do this in frontend code
const response = await fetch('https://api.gett-tech.com/v1/marketfront/session/create', {
  headers: { 'Authorization': `Bearer ${API_KEY}` } // Exposed!
});

// Always call from your backend
const response = await yourBackend.createGettSession(userId);
```

### Session Token Handling

Session tokens are safe for client-side use but should still be handled carefully:

- Tokens are scoped to a single session and user
- Tokens cannot be used to create new sessions
- Tokens expire automatically

### Data Privacy

- User data is processed according to Gett's privacy policy
- You are responsible for obtaining appropriate consent from your users
- Gett does not share user data with third parties

---

## Error Handling

### Session Creation Errors

| Error Code | HTTP Status | Description | Resolution |
|------------|-------------|-------------|------------|
| `invalid_api_key` | 401 | API key is invalid or revoked | Verify your API key |
| `invalid_email` | 400 | Email format is invalid | Provide valid email |
| `invalid_phone` | 400 | Phone format is invalid | Use E.164 format |
| `invalid_address` | 400 | Address could not be validated | Verify address fields |
| `rate_limited` | 429 | Too many requests | Implement backoff |

### Session Token Errors

| Error Code | HTTP Status | Description | Resolution |
|------------|-------------|-------------|------------|
| `session_expired` | 401 | Session token has expired | Create a new session |
| `session_invalid` | 401 | Session token is malformed or revoked | Create a new session |
| `session_not_found` | 404 | Session does not exist | Create a new session |

---

## Next Steps

- [Payments](/distribution-partners/shared-guides/payments) — Card-on-File setup and payment interchange
- [Events](/distribution-partners/marketfront-sdk/guides/events) — Handle order lifecycle events
- [SDK Reference](/distribution-partners/marketfront-sdk/sdk-reference) — Complete SDK API documentation
