<!-- llms.txt: https://workos.com/llms.txt -->
<!-- feedback.md: https://workos.com/docs/feedback.md -->

# JWT Templates

## Introduction

JWT templates allow you to customize the claims in your application's access tokens issued by WorkOS. You can leverage core attributes of users and organizations, in addition to [custom metadata](https://workos.com/docs/authkit/metadata) you set on these objects.

***

## Which tokens a template renders into

A JWT template renders into every access token the environment issues through a user sign-in or consent flow: AuthKit session tokens, and [WorkOS Connect](https://workos.com/docs/authkit/connect) access tokens issued to OAuth applications and to MCP clients registered through Dynamic Client Registration or Client ID Metadata Document. There is one template per environment and no per-application template.

A template does not render into tokens from the `client_credentials` grant used by [M2M applications](https://workos.com/docs/authkit/connect/m2m), because that grant has no user or organization membership to render against. Those tokens carry a fixed claim set.

Permissions aren't available in the template context. A template that references `organization_membership.permissions` fails validation with `Invalid path`; `organization_membership.role` and `organization_membership.roles` are available. See [Connect access token claims](https://workos.com/docs/authkit/connect/token-claims) for the claim set per grant type and how to check permissions server-side.

***

## Create a JWT template

JWT templates can be managed in the Authentication page within the [WorkOS Dashboard](https://dashboard.workos.com/environment/authentication/features). The JWT Template can be found within Features.

JWT templates are comprised of a template string which is rendered with the user and organization context after a user successfully authenticates.

## Example usage

:::code-group

```js language="js" title="Template" tab="js-1"
{
    "urn:myapp:full_name": "{{ user.first_name || 'Someone' }} {{ user.last_name || 'Unknown' }}",
    "urn:myapp:email": {{ user.email }},
    "urn:myapp:organization_tier": "{{ organization.metadata.tier || 'bronze' }}",
    "urn:myapp:user_language": "{{ user.metadata.language || 'en' }}",
    "urn:myapp:organization_domain": "{{ organization.domains.0.domain }}"
}
```

```js language="js" title="Context" tab="js-2"
{
    "user": {
        "id": "user_01JNS7VK1HMX7CT0C6V4ZHZZNX",
        "metadata": {
            "language": "es"
        },
        "object": "user",
        "created_at": "2021-01-01T00:00:00.000Z",
        "updated_at": "2021-01-01T00:00:00.000Z",
        "email": "user@example.com",
        "first_name": "User",
        "last_name": "Test",
        "email_verified": true,
        "profile_picture_url": "https://example.com/profile.jpg",
        "external_id": "user_123"
    },
    "organization": {
        "name": "Test Organization",
        "id": "org_01JNS7VK1HMX7CT0C6V4ZHZZNX",
        "metadata": {},
        "object": "organization",
        "created_at": "2021-01-01T00:00:00.000Z",
        "updated_at": "2021-01-01T00:00:00.000Z",
        "allow_profiles_outside_organization": false,
        "domains": [
            {
                "id": "org_domain_01JNS7VK1HMX7CT0C6V4ZHZZNX",
                "domain": "acme.com",
                "object": "organization_domain",
                "organization_id": "org_01JNS7VK1HMX7CT0C6V4ZHZZNX",
                "state": "verified"
            },
            {
                "id": "org_domain_01JNS7VK1HMX7CT0C6V4ZHZZNY",
                "domain": "example.com",
                "object": "organization_domain",
                "organization_id": "org_01JNS7VK1HMX7CT0C6V4ZHZZNX",
                "state": "verified"
            }
        ],
        "stripe_customer_id": "cus_123",
        "external_id": "org_123"
    },
    "organization_membership": {
        "id": "om_01JNS7VK1HMX7CT0C6V4ZHZZNX",
        "object": "organization_membership",
        "role": "member",
        "roles": ["member"],
        "custom_attributes": {
            "department": "Engineering",
            "job_title": "Software Engineer"
        },
        "created_at": "2021-01-01T00:00:00.000Z",
        "updated_at": "2021-01-01T00:00:00.000Z"
    }
}
```

```js language="js" title="Output" tab="js-3"
{
    "urn:myapp:full_name": "User Test",
    "urn:myapp:email": "user@example.com",
    "urn:myapp:organization_tier": "bronze",
    "urn:myapp:user_language": "es",
    "urn:myapp:organization_domain": "acme.com"
}
```

:::

***

## Custom attributes

You can include IdP-sourced attributes in your JWT claims using the `organization_membership.custom_attributes` context. These attributes are available from the linked [Directory User](https://workos.com/docs/reference/directory-sync/directory-user) or [SSO Profile](https://workos.com/docs/reference/sso/profile).

To configure custom attributes, see the [IdP Attributes](https://workos.com/docs/sso/attributes) guide for SSO or the [User Attributes](https://workos.com/docs/directory-sync/attributes) guide for Directory Sync.

### Example

:::code-group

```js language="js" title="Template" tab="js-1"
{
    "urn:myapp:department": {{ organization_membership.custom_attributes.department }},
    "urn:myapp:job_title": {{ organization_membership.custom_attributes.job_title }},
    "urn:myapp:cost_center": {{ organization_membership.custom_attributes.cost_center || "default" }}
}
```

```js language="js" title="Context" tab="js-2"
{
    "user": {
        "id": "user_01JNS7VK1HMX7CT0C6V4ZHZZNX",
        "email": "user@example.com"
    },
    "organization": {
        "id": "org_01JNS7VK1HMX7CT0C6V4ZHZZNX",
        "name": "Acme Corp"
    },
    "organization_membership": {
        "id": "om_01JNS7VK1HMX7CT0C6V4ZHZZNX",
        "object": "organization_membership",
        "role": "member",
        "roles": ["member"],
        "custom_attributes": {
            "department": "Engineering",
            "job_title": "Software Engineer"
        },
        "created_at": "2021-01-01T00:00:00.000Z",
        "updated_at": "2021-01-01T00:00:00.000Z"
    }
}
```

```js language="js" title="Output" tab="js-3"
{
    "urn:myapp:department": "Engineering",
    "urn:myapp:job_title": "Software Engineer",
    "urn:myapp:cost_center": "default"
}
```

:::

### Priority rules

When a membership is linked to both a Directory User and an SSO Profile, the Directory User's `custom_attributes` take precedence. This ensures consistent data when both IdP sources are configured.

***

## Syntax

### 1. **Basic Variable Interpolation**

You can reference variables inside the template.

:::code-group

```js language="js" title="Template" tab="js-1"
{
    "user": {{ user.first_name }}
}
```

```js language="js" title="Context" tab="js-2"
{
    "user": {
      "first_name": "Alice"
    }
  }
```

```js language="js" title="Output" tab="js-3"
{
    "user": "Alice"
}
```

:::

### 2. **Fallback Values** (`||` operator)

If the first value is `null` or undefined, the next value in the fallback chain is used.

:::code-group

```js language="js" title="Template" tab="js-1"
{
    "user": {{ user.metadata.nickname || user.email }}
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {
    "email": "alice@example.com"
  }
}
```

```js language="js" title="Output" tab="js-3"
{
    "user": "alice@example.com"
}
```

:::

### 3. **String Literals**

Strings can be used as fallback values.

:::code-group

```js language="js" title="Template" tab="js-1"
{
    "user": {{ user.metadata.nickname || 'Guest' }}
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {}
}
```

```js language="js" title="Output" tab="js-3"
{
    "user": "Guest"
}
```

:::

### 4. **Concatenation in Strings**

Multiple variables can be used within a single string.

:::code-group

```js language="js" title="Template" tab="js-1"
{
    "user": "{{ user.first_name }} {{ user.last_name }}"
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {
    "first_name": "Alice",
    "last_name": "Smith"
  }
}
```

```js language="js" title="Output" tab="js-3"
{
    "user": "Alice Smith"
}
```

:::

### 5. **Object Interpolation**

Interpolating entire objects and arrays is allowed if they are valid JSON objects. This is not allowed inside string literals and will throw a validation error.

:::code-group

```js language="js" title="Template" tab="js-1"
{
  "metadata": {{ user.metadata }}
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {
    "metadata": {
      "role": "admin"
    }
  }
}
```

```js language="js" title="Output" tab="js-3"
{
    "metadata": {
        "role": "admin"
    }
}
```

:::

### 6. **Reserved Keys Restriction**

The following keys cannot be used in templates:

- `iss`
- `sub`
- `exp`
- `iat`
- `nbf`
- `jti`
- `act`

Any attempt to use these keys will result in a validation error.

## Whitespace Handling

The rendering engine trims whitespace from the beginning and end of string values.

## Error Handling

If the template contains invalid syntax, an error will be thrown:

- **Template must render to an object with at least one explicitly defined top-level key:** If the template does not evaluate to a valid JSON object (e.g., an array or primitive value). Example:
  ```js
  [ {{ user.email }} ]
  ```
- **Keys reserved (`iss`, `sub`, `exp`, etc.):** These keys cannot be used in the template.
  ```js
  { "iss": {{ user.email }} }
  ```
- **String encapsulated expression cannot contain object reference:** Objects cannot be interpolated inside a string.
  ```js
  { "user": "{{ user.metadata }}" }
  ```
- **Invalid expression segment:** Logical operators (`||` with empty operands) or malformed expressions are not allowed.
  ```js
  {{ user.email && user user }}
  {{ user.email || || user.email }}
  ```
- **Template parse error: missing '}}':** A template block was opened but never closed.
  ```js
  {{ user.id
  ```
- **Expression cannot be empty:** An empty expression inside `{{ }}` is invalid.
  ```html
  {{}}
  ```
- **Missing closing braces:** `Template parse error: missing '}}'`
- **Invalid key usage:** `Keys reserved (iss, sub, exp, etc.)`
- **Unknown variables:** `Invalid path: "unknown.variable"`

## Null Handling

JWT templates provide built-in handling for `null` values to ensure access tokens only contain populated claims.

### **1. Removing Top-Level Null Values**

If an expression evaluates to `null`, the corresponding key is removed from the final JSON output.

#### **Example**

:::code-group

```js language="js" title="Template" tab="js-1"
{
  "user": {{ user.metadata.favorite_color }},
  "organization_tier": {{ organization.metadata.tier }}
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {
    "metadata": {}
  },
  "organization": {
    "metadata": {
      "tier": "bronze"
    }
  }
}
```

```js language="js" title="Output" tab="js-3"
{
    "organization_tier": "bronze"
}
```

:::

### **2. Handling Null Values in Concatenated Strings**

If a `null` value appears in a string concatenation, it is replaced with an empty string (`""`) instead of being removed.

:::code-group

```js language="js" title="Template" tab="js-1"
{
  "user": "{{ user.first_name }} {{ user.last_name }}"
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {
    "first_name": "Alice",
    "last_name": null
  }
}
```

```js language="js" title="Output" tab="js-3"
{
    "user": "Alice"
}
```

:::

### **3. Using Fallbacks to Avoid Null Values**

The `||` operator can be used to provide a fallback value when an expression evaluates to `null`.

:::code-group

```js language="js" title="Template" tab="js-1"
{
  "external_id": {{ user.external_id || 'unknown' }}
}
```

```js language="js" title="Context" tab="js-2"
{
  "user": {
    "external_id": null
  }
}
```

```js language="js" title="Output" tab="js-3"
{
  "external_id": "unknown"
}
```

:::

## Size limits

JWT templates must render to a JSON object that is 3072 bytes or smaller due to cookie size constraints in web browsers.
