# Connect an API with custom JSON auth

> Store several secrets and a JSON template that places each in the request, then call the API with ctx.http.authed. Headers, bodies, paths, Basic.

When an API wants more than one secret, or wants a secret somewhere the other generic services don't put one, use the **Custom JSON Auth Template** service. You store the secrets and a short JSON template that says where each one goes: a header, a query parameter, a body field, a cookie, a Basic credential, or the URL path. Your function then calls the API with `ctx.http.authed('alias')`, and Helix applies the template server-side. Helix never hands the stored secrets to your code, though an API can echo them back (see [security notes](#security-notes)).

## When to use it

Start with the generic services in [connect an API that isn't listed](/documentation/guides/connect-any-api/). Use this service when none of them fits.

| If the API expects | Use |
|---|---|
| One token as a bearer token, or as a Basic password | HTTP Bearer Token, or HTTP Basic Authentication |
| One token in one header or one query parameter | Custom Token Authentication |
| A signature computed over the request | HTTP HMAC signature, OAuth 1.0a, or AWS Signature v4 |
| Two or more secrets in headers, such as a key and a secret | **Custom JSON Auth Template** |
| A secret inside the JSON or form body | **Custom JSON Auth Template** |
| A secret in the URL path, or in a cookie | **Custom JSON Auth Template** |
| A secret that has to be Base64-encoded first | **Custom JSON Auth Template** |

The template injects stored values. It doesn't compute signatures, fetch tokens, or refresh anything. If the API needs a token exchange or a signature, use a service that does that.

## Create the authentication

Run `helix auth connect --new`:

```bash
helix auth connect --new
```

The command opens the dashboard's connect page for your workspace. Add `--no-open` to print the link instead. In the dashboard, choose **Custom JSON Auth Template** and name the authentication. The form has three fields. The [reference](/documentation/reference/custom-json-auth-template/) has the full rules for each.

| Field | What to enter |
|---|---|
| **Secrets** | A list of secrets. Add one entry per secret, with a **Name** and a **Value**. The template refers to each secret by its name. The value is masked as you type it. You can add 1 to 50 secrets, and each name must be unique |
| **Injection template** | The JSON that places the secrets in the request. Type or paste it as text. The form stores it as written, and Helix reads it as JSON when it applies the authentication |
| **Pin to domain** | The only domain the secrets may be sent to, such as `api.vendor.com`. Subdomains are included. Enter the bare domain: no `https://`, path, wildcard, or port. Use the narrowest domain the API allows (see [security notes](#security-notes)) |

A secret name is 1 to 64 letters, digits, or underscores, and can't start with a digit, as in `api_key`. Saving the form doesn't check the template or that names are unique. A mistake in either shows up when your function first makes a call (see [troubleshooting](#troubleshooting)).

A template has a `version` of `1` (the current version) and a list of `inject` rules. Each rule names a place (`in`) and a value that refers to a secret as `{{name}}`:

```json
{
  "version": 1,
  "inject": [
    { "in": "header", "name": "X-Api-Key", "value": "{{api_key}}" }
  ]
}
```

The CLI writes the alias into `helix.config.ts` once it finds the new authentication. You can also add one yourself with `helix auth add <alias> <uuid>`.

## Add it to helix.config.ts

```typescript
// helix.config.ts
import { defineConfig } from '@trayai/helix-sdk';

export default defineConfig({
  name: 'vendor-sync',
  workspaceId: 'f8e7d6c5-4b3a-2190-8765-abcdef012345',
  projectId: 'a1b2c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d',

  authentications: {
    vendor_api: '1a0fbf5c-2c9e-4aa1-ada3-ccbba65019ab',
  },
});
```

## Call the API

```typescript
// functions/api/v1/orders.get.ts
import { defineFunction } from '@trayai/helix-sdk';

export default defineFunction(async (ctx) => {
  const res = await ctx.http
    .authed('vendor_api')
    .get('https://api.vendor.com/v2/orders', { query: { status: 'open' } });

  return { status: res.status, orders: res.body };
});
```

An authed call returns `{ status, body, headers }`. A non-2xx answer from the API comes back in `status`, so check it when you need to handle errors. A template or request that Helix rejects before sending is different: the call throws an `SdkError` with status 400 and code `invalid_authenticated_request`, and nothing reaches the API. See [ctx.http](/documentation/reference/context/http/) for every option.

To handle a rejection, catch the error:

```typescript
// functions/api/v1/orders.get.ts
import { defineFunction } from '@trayai/helix-sdk';

export default defineFunction(async (ctx) => {
  try {
    const res = await ctx.http.authed('vendor_api').get('https://api.vendor.com/v2/orders');
    return { status: res.status, orders: res.body };
  } catch (error) {
    if (error instanceof Error && error.name === 'SdkError') {
      ctx.log.error('Vendor auth template rejected', { message: error.message });
      throw ctx.error(502, 'Vendor credentials are misconfigured');
    }
    throw error;
  }
});
```

The message never includes a secret, so it is safe to log.

## Examples

Each example lists the secrets to add to the **Secrets** list and the JSON to put in **Injection template**. Each template is complete and valid. Replace the names and the pinned domain with your API's.

### Two secrets in headers

An API that wants a key and a secret in separate headers.

Secrets:

| Name | Value |
|---|---|
| `api_key` | `k-1234` |
| `api_secret` | `s-5678` |

Injection template:

```json
{
  "version": 1,
  "inject": [
    { "in": "header", "name": "X-Api-Key", "value": "{{api_key}}" },
    { "in": "header", "name": "X-Api-Secret", "value": "{{api_secret}}" }
  ]
}
```

Pin to domain: `api.vendor.com`. Your function sets neither header. If it passes an `X-Api-Key` header of its own, the template's value replaces it.

To see the result without a real account, make the secrets up, pin the authentication to `httpbin.org`, and call `https://httpbin.org/headers`. The response lists `X-Api-Key` and `X-Api-Secret` with your made-up values. Don't use real secrets with an echo endpoint.

### Credentials in the request body

An API that takes a client ID and secret inside a JSON body.

Secrets:

| Name | Value |
|---|---|
| `client_id` | `cid-1234` |
| `client_secret` | `cs-5678` |

Injection template:

```json
{
  "version": 1,
  "inject": [
    { "in": "body", "name": "auth.client_id", "value": "{{client_id}}" },
    { "in": "body", "name": "auth.client_secret", "value": "{{client_secret}}" }
  ]
}
```

Your function sends the rest of the body:

```typescript
const res = await ctx.http
  .authed('vendor_api')
  .post('https://api.vendor.com/v2/reports', { body: { report: 'weekly' } });
```

The API receives `{ "report": "weekly", "auth": { "client_id": "cid-1234", "client_secret": "cs-5678" } }`. Helix creates the `auth` object when your body doesn't have one. A body rule works on JSON bodies and on `application/x-www-form-urlencoded` bodies, and it fails on a `GET` or `HEAD` request.

Helix parses the JSON body and serializes it again, so an integer beyond 2^53 loses precision and a duplicate key collapses into one. A form body is re-encoded: a standard decoder reads the same fields, but the bytes differ. Pass an object as `body`, as above. A string body needs a `Content-Type` header, or the body rule rejects the call. If you send no body and no `Content-Type`, Helix builds a JSON body from the rule and sends it as `application/json`. If you send no body and a form `Content-Type`, Helix builds a form body from the rule. A body-less call with any other content type is rejected.

### A token in the URL path

An API in the style of Telegram's bot API, where the token is part of the path.

Secrets:

| Name | Value |
|---|---|
| `bot_token` | `123456789:AAH-made-up-token` |

Injection template:

```json
{
  "version": 1,
  "inject": [
    { "in": "path", "placeholder": "BOT_TOKEN", "value": "{{bot_token}}" }
  ]
}
```

Pin to domain: `api.telegram.org`. The placeholder is 8 to 64 uppercase letters, digits, and underscores, with at least one underscore, as in `BOT_TOKEN`. A plain word such as `accounts` can never be a placeholder. Put the placeholder text in the URL:

```typescript
const res = await ctx.http
  .authed('chat_bot')
  .get('https://api.telegram.org/botBOT_TOKEN/getMe');
```

Helix replaces `BOT_TOKEN` with the token before sending. The value is percent-encoded when it goes in, so the `:` in the token above is sent as `%3A`. Check that your API accepts the encoded form. Helix finds the placeholder as plain text anywhere in the path, so `/botBOT_TOKEN/getMe` works. Choose placeholder text that can't appear anywhere else in a real path. The path ends at the first `?` or `#`, so a placeholder that appears only in the query string or after a `#` counts as not found. A URL that doesn't contain the placeholder is rejected. A secret that would turn a path segment into `.` or `..` is also rejected. So is a path that already has a `.` or `..` segment, however the dots are written (`..`, `%2e%2e`, `%2E`, or a mix such as `.%2E`).

The secret is now part of the URL. Where you put the placeholder decides where it lands, so use a path rule only when the API leaves you no choice.

### Basic credentials and an extra header

An API that uses Basic authentication and also wants an account ID in a header.

Secrets:

| Name | Value |
|---|---|
| `api_user` | `svc-reports` |
| `api_token` | `t-1234` |
| `account_id` | `acct-42` |

Injection template:

```json
{
  "version": 1,
  "inject": [
    { "in": "basic", "username": "{{api_user}}", "password": "{{api_token}}" },
    { "in": "header", "name": "X-Account-Id", "value": "{{account_id}}" }
  ]
}
```

The API receives `Authorization: Basic ...` built from the user and token, and `X-Account-Id: acct-42`. If the username is a fixed word such as `api`, write it as literal text (`"username": "api"`) and keep the placeholder in the password. If the API takes its key as the username and ignores the password, put the placeholder in `username` and write the password as an empty string (`"password": ""`). The username can't be empty.

Don't combine a `basic` rule with a header rule named `Authorization`. Both write the same header, so the template is rejected.

## Troubleshooting

A bad template or request makes the call throw an `SdkError` with status 400 and code `invalid_authenticated_request`. Every template or rendering error is found before anything is sent to the API, so the API never sees a partial credential. The message starts with "custom JSON authentication", names the specific problem (such as an unknown filter or an unclosed placeholder), names the field, the rule's position in `inject` (counting from zero), or the secret's name, and says what to fix. It never includes a secret value.

| Cause | Fix |
|---|---|
| The call throws instead of returning a status | Helix rejected the template or request before sending it. Catch the `SdkError` and read its message, as in [Call the API](#call-the-api) |
| A placeholder names a secret that isn't stored | Match the name in `{{...}}` to the **Name** of an entry in **Secrets**. Names are case-sensitive |
| Two secrets have the same name | Rename or remove one. Each name in **Secrets** must be unique |
| Unknown filter, or an unclosed placeholder | Use only `base64` or `base64url`, and close every placeholder with `}}` |
| A value has no placeholder, or its literal text is malformed | Add a placeholder. A rule made only of literal text is rejected. Literal text that contains a lone surrogate is rejected too ("contains malformed text") |
| The template is missing, over its size limit, or not valid JSON | Edit the authentication and check the **Injection template** text is one JSON object. It can be at most 16 KiB, counted in UTF-8 bytes. A common cause is a trailing comma or a smart quote pasted from a document |
| The secrets are over their size limit | The whole **Secrets** list can be at most 64 KiB, counted in UTF-8 bytes. Store only the secrets the template uses |
| The template's `version` isn't `1` | Set `"version": 1`. Any other version is rejected |
| An unknown key in the template or a rule | Remove it. Templates are strict, and the reference lists the keys each rule takes |
| Two rules write to the same place | Merge them or rename one. A `basic` rule and an `Authorization` header rule collide |
| A header value or cookie value has a character that isn't allowed | Encode the secret with `{{ name \| base64url }}`, but only if the API accepts the encoded form |
| A header rule is denied | Some headers can't be set by a template. Examples are connection and framing headers, `Cookie`, `Content-*`, `Accept*`, `User-Agent`, and method-override headers. The [reference](/documentation/reference/custom-json-auth-template/#header) has the full list. The error names the header. Send the secret in another header, a body field, or a cookie (use the cookie rule, not a `Cookie` header) |
| A body rule fails | Check the request has a JSON or form body, isn't a `GET` or `HEAD`, and that every step of a dotted name is an object. Pass an object as `body`, or set `Content-Type` when you send a string |
| A path placeholder isn't found, or the path is rejected | Put the exact placeholder text in the URL path, before any `?` or `#`. A placeholder is 8 to 64 uppercase letters, digits, and underscores, with at least one underscore. Neither a secret nor the path you pass can contain a `.` or `..` segment, including `%2e` and `%2E` forms |
| The request fails because of the host | The URL's host must be the pinned domain or a subdomain of it |
| The URL starts with `http://` | Use `https://`. Helix rejects `http://` with a 400 and never upgrades it |
| The pin is rejected when you save the authentication | Enter a bare domain with at least two parts, such as `api.vendor.com`. An IP address, a single word like `com`, and common public suffixes like `co.uk` or `com.au` are rejected |
| The API answers 301, 302, or another 3xx | Helix doesn't follow redirects. The 3xx comes back in `res.status` with its `location` header. Check where it points before you follow it: a new request is injected and checked against the pin again |
| The API answers 401 | The API's answer is returned, not thrown: read `res.status`. Check the secrets and where the API expects them |
| A missing alias error | The alias isn't in `helix.config.ts`. The error lists the aliases that are configured |

## Security notes

- **The domain pin is required.** The secrets can only be sent to the pinned domain and its subdomains, which limits any exposure to that one domain.
- **Pin as narrowly as the API allows.** Pin to `api.vendor.com` rather than `vendor.com` when the API lives on one host. Helix rejects a pin that is a bare top-level domain, an IP address, or a common public suffix such as `co.uk` or `com.au`, but that check uses a short list, not the full public suffix list. A broad domain that someone else can register under, such as `amazonaws.com`, is accepted and would let the secrets go to every host under it.
- **Requests are HTTPS only.** A URL that starts with `http://` is rejected with a 400. Helix never upgrades it, so a secret is never sent in clear text.
- **Redirects are not followed.** A 3xx answer comes back to your code as it is, so an injected credential never follows a redirect to another place. If you follow it yourself, that is a new request: Helix injects the credential and checks the pin again.
- **An API can echo a secret back.** Helix never hands the stored secrets to your code, but an API can return them: an echo endpoint, a redirect `location` header, or an error message or 404 page that quotes the URL. You choose the endpoint and, for a path rule, where the placeholder sits, so prefer header or body rules.
- **Prefer headers and bodies.** The `query` and `path` rules put the secret in the URL, and the API or anything between you and it can log the URL. Use them only when the API gives you no choice.
- **Keep each authentication small.** Store only the secrets the template uses. Every function in the project that uses the alias can make calls with them.
- **Values are never expanded twice.** A secret that contains `{{x}}` is sent as written.

For the exact syntax, limits, and every rule, see the [custom JSON auth template reference](/documentation/reference/custom-json-auth-template/). For how aliases and credential injection work in general, see [connected services](/documentation/guides/connected-services/).

---

Canonical: https://helix.tray.ai/documentation/guides/custom-json-auth/
Any link on this page is available as markdown by appending .md to its URL.
Full corpus: https://helix.tray.ai/documentation/llms-full.txt