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

# Create session

> Create a Session and trigger its first run in one atomic call. A Session is the durable identity for a bi-directional stream of records (the `.in` and `.out` channels) that survives across the runs processing it.

Idempotent on `externalId` within an environment. Calling create again with an `externalId` that already maps to an open session returns the existing session with `isCached: true` and `201` becomes `200`. Reusing an `externalId` whose session is already closed or expired returns `409`.

Authorize with a secret key, or a public token carrying `write:sessions` for the session you are creating.



## OpenAPI

````yaml v3-openapi POST /api/v1/sessions
openapi: 3.1.0
info:
  title: Trigger.dev v3 REST API
  description: >-
    The REST API lets you trigger and manage runs on Trigger.dev. You can
    trigger a run, get the status of a run, and get the results of a run. 
  version: 2024-04
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
  - url: https://api.trigger.dev
    description: Trigger.dev API
security: []
paths:
  /api/v1/sessions:
    post:
      tags:
        - sessions
      summary: Create a session
      description: >-
        Create a Session and trigger its first run in one atomic call. A Session
        is the durable identity for a bi-directional stream of records (the
        `.in` and `.out` channels) that survives across the runs processing it.


        Idempotent on `externalId` within an environment. Calling create again
        with an `externalId` that already maps to an open session returns the
        existing session with `isCached: true` and `201` becomes `200`. Reusing
        an `externalId` whose session is already closed or expired returns
        `409`.


        Authorize with a secret key, or a public token carrying `write:sessions`
        for the session you are creating.
      operationId: create_session_v1
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSessionRequestBody'
      responses:
        '200':
          description: >-
            An open session already existed for this `externalId`. The existing
            session is returned with `isCached: true`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreatedSessionResponseBody'
        '201':
          description: Session created and its first run triggered.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreatedSessionResponseBody'
        '401':
          description: Unauthorized
        '409':
          description: >-
            An `externalId` was reused, but its session is already closed or
            expired. Closed and expired sessions cannot be reopened.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: >-
            Validation failed — for example the request body exceeds 32KB, or
            `externalId` starts with the reserved `session_` prefix.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorWithDetailsResponse'
      security:
        - secretKey: []
        - publicAccessToken: []
      x-codeSamples:
        - lang: typescript
          label: Start a session
          source: >-
            import { sessions } from "@trigger.dev/sdk";


            const { id, runId, publicAccessToken, isCached } = await
            sessions.start({
              type: "chat.agent",
              externalId: chatId,
              taskIdentifier: "my-chat",
              triggerConfig: {
                basePayload: { chatId },
                tags: [`chat:${chatId}`],
              },
            });


            console.log(id);       // e.g. "session_abc123"

            console.log(runId);    // the first run, e.g. "run_def456"

            console.log(isCached); // false on a brand-new session
components:
  schemas:
    CreateSessionRequestBody:
      type: object
      description: >-
        Body for `POST /api/v1/sessions`. The whole body must be 32KB or
        smaller.
      required:
        - type
        - taskIdentifier
        - triggerConfig
      properties:
        type:
          type: string
          minLength: 1
          maxLength: 64
          description: >-
            Free-form discriminator for the session, e.g. `chat.agent`. Not
            validated against an enum.
          example: chat.agent
        taskIdentifier:
          type: string
          minLength: 1
          maxLength: 128
          description: The task this session triggers runs against.
          example: my-chat
        triggerConfig:
          $ref: '#/components/schemas/SessionTriggerConfig'
        externalId:
          type: string
          minLength: 1
          maxLength: 256
          description: >-
            Your stable identity for the session, unique per environment. Cannot
            start with the reserved `session_` prefix. Reusing an `externalId`
            makes create idempotent; reusing one whose session is closed or
            expired returns `409`.
          example: chat_1234
        tags:
          type: array
          maxItems: 10
          items:
            type: string
            maxLength: 128
          description: Up to 10 tags on the session row, for dashboard filtering.
        metadata:
          type: object
          additionalProperties: true
          description: Arbitrary JSON metadata.
        expiresAt:
          type: string
          format: date-time
          description: Absolute expiry timestamp for retention.
    CreatedSessionResponseBody:
      allOf:
        - $ref: '#/components/schemas/SessionObject'
        - type: object
          required:
            - runId
            - publicAccessToken
            - isCached
          properties:
            runId:
              type: string
              description: Friendly ID of the first run triggered alongside the session.
              example: run_def456
            publicAccessToken:
              type: string
              description: >-
                Session-scoped public access token carrying
                `read:sessions:{key}` and `write:sessions:{key}`. Default TTL is
                1 hour. Safe to pass to frontend clients.
            isCached:
              type: boolean
              description: >-
                `true` if an open session already existed for this `externalId`
                (idempotent upsert), `false` if newly created.
    ErrorResponse:
      type: object
      properties:
        error:
          type: string
          example: Something went wrong
      required:
        - error
    ErrorWithDetailsResponse:
      type: object
      properties:
        error:
          type: string
          example: Query Error
        details:
          type: array
          items:
            type: object
            required:
              - code
              - message
            properties:
              code:
                type: string
                description: The error code
                example: custom
              message:
                type: string
                description: The error message
                example: 'Invalid status values: FOOBAR'
              path:
                type: array
                items:
                  type: string
                description: The relevant path in the request
                example:
                  - filter[status]
      required:
        - error
    SessionTriggerConfig:
      type: object
      description: >-
        Trigger options applied to every run a session schedules. `basePayload`
        is the wire payload merged into each run; the remaining fields map onto
        the standard trigger options.
      required:
        - basePayload
      properties:
        basePayload:
          type: object
          additionalProperties: true
          description: >-
            Base payload passed to every run this session triggers. For
            `chat.agent` this carries `{ chatId, ...clientData }`.
        machine:
          type: string
          description: Machine preset for each run, e.g. `small-1x`.
          example: small-1x
        queue:
          type: string
          maxLength: 128
          description: Queue to schedule runs on.
        tags:
          type: array
          maxItems: 5
          items:
            type: string
            maxLength: 128
          description: Tags applied to every run this session triggers.
        maxAttempts:
          type: integer
          minimum: 1
          maximum: 10
          description: Maximum retry attempts per run.
        maxDuration:
          type: integer
          minimum: 1
          description: Per-run wall-clock cap in seconds.
        lockToVersion:
          type: string
          description: Pin every run to a specific worker version.
          example: '20240523.1'
        region:
          type: string
          description: Region to schedule runs in.
        idleTimeoutInSeconds:
          type: integer
          minimum: 1
          maximum: 3600
          description: Idle timeout surfaced to `chat.agent` via the wire payload.
    SessionObject:
      type: object
      description: A session row.
      required:
        - id
        - type
        - taskIdentifier
        - tags
        - createdAt
        - updatedAt
      properties:
        id:
          type: string
          description: The session's friendly ID, prefixed with `session_`.
          example: session_abc123
        externalId:
          type: string
          nullable: true
          description: Your stable identity for the session, if one was set.
          example: chat_1234
        type:
          type: string
          description: The session type discriminator.
          example: chat.agent
        taskIdentifier:
          type: string
          description: The task this session triggers runs against.
          example: my-chat
        triggerConfig:
          $ref: '#/components/schemas/SessionTriggerConfig'
        currentRunId:
          type: string
          nullable: true
          description: >-
            Friendly ID of the live run for this session, if any. Prefixed with
            `run_`. Omitted on list rows.
          example: run_def456
        tags:
          type: array
          items:
            type: string
          description: Tags on the session row.
          example:
            - chat:1234
        metadata:
          type: object
          additionalProperties: true
          nullable: true
          description: Arbitrary JSON metadata, or `null` if unset.
        closedAt:
          type: string
          format: date-time
          nullable: true
          description: When the session was closed, or `null` if open.
        closedReason:
          type: string
          nullable: true
          description: The optional reason recorded when the session was closed.
        expiresAt:
          type: string
          format: date-time
          nullable: true
          description: The session's retention deadline, or `null` if none.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
  securitySchemes:
    secretKey:
      type: http
      scheme: bearer
      description: >
        Use your project-specific Secret API key. Will start with `tr_dev_`,
        `tr_prod`, `tr_stg`, etc.


        You can find your Secret API key in the API Keys section of your
        Trigger.dev project dashboard.


        Our TypeScript SDK will default to using the value of the
        `TRIGGER_SECRET_KEY` environment variable if it is set. If you are using
        the SDK in a different environment, you can set the key using the
        `configure` function.


        ```typescript

        import { configure } from "@trigger.dev/sdk";


        configure({ accessToken: "tr_dev_1234" });

        ```
    publicAccessToken:
      type: http
      scheme: bearer
      description: >
        A short-lived JWT scoped to specific resources, returned as
        `publicAccessToken` from APIs

        such as `wait.createToken()` / `POST /api/v1/waitpoints/tokens` and

        `sessions.start()` / `POST /api/v1/sessions`, or minted directly with
        `auth.createPublicToken()`.


        This token is safe to embed in frontend clients — it can only act on the
        resources its

        scopes grant (e.g. `read:sessions:{id}`, `write:sessions:{id}`) and
        cannot be used for any

        other API operations. For session tokens see the [session
        scopes](/management/authentication#session-scopes).

````