> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/first-script.md).

# First script

Build, wire and verify a pass data provider script that reads a member's points from an external API, with caching and a soft failure when the API is down.

The most common scripting need is to show on a pass a value that lives in another system: a points balance, a tier, a next appointment. The extension point for it is the pass data provider. The platform asks the script for data each time a pass is rendered, the script fetches it, and the pass type's templates use the values. The example is deliberately small, but it contains the three habits that every production script needs: a cache, a guard on missing input, and a soft failure.

For the full reference of the extension point, see [Pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md). For other needs, see the table in [Scripting](https://docs.thewalletcrew.io/developers-guides/scripting.md).

<details>

<summary><strong>Real-world examples</strong></summary>

* A loyalty pass shows the current points balance read from a CRM with a five-minute cache.
* A gift card pass shows the remaining amount read from an ERP.
* A ticket pass shows a seat or an access zone read from a ticketing export.
* A membership pass shows a tier label computed by a recommendation service.

</details>

## What gets built

The script is called `memberLookup`. For a pass that carries an identifier `memberId`, it calls `https://api.example.com/v1/members/{memberId}` with an API key kept in the tenant's secrets, caches the answer for five minutes, and writes `points` and `tier` for the templates. If the member does not exist, or the API fails, the script reports that nothing was found and the pass is still rendered, without those values.

Three names have to agree, and most failures of a first script come from a mismatch between them:

| Name             | Value in the example                               | Where it appears                                                          |
| ---------------- | -------------------------------------------------- | ------------------------------------------------------------------------- |
| Script id        | `memberLookup`                                     | Last part of the registration key, and `scriptId` in the pass type        |
| Registration key | `runtime.scriptable.passDataProvider.memberLookup` | `context.register(...)` in the file                                       |
| Namespace        | `memberLookup`                                     | Prefix of the keys that templates read, for example `memberLookup.points` |

The file name does not matter to the platform, but naming the file after the script id (`memberLookup.js`) keeps the configuration readable.

## Step 1: create the secret

The API key must not be written in the script or in YAML. It goes into the tenant's secrets, managed in the admin console, as described in [API keys and secrets](https://docs.thewalletcrew.io/configure/advanced-configuration/platform/api-keys-and-secrets.md). The key rules are in [twc/secrets](https://docs.thewalletcrew.io/developers-guides/scripting/modules/secrets.md#keys). The example uses `MEMBER-API-KEY`.

## Step 2: create the script file

In the admin console, the advanced configuration is under **Settings → Advanced → Advanced configuration**. Creating the file `server/scripts/memberLookup.js` there, with the content below, defines the script.

```js
import { getSecret } from 'twc/secrets';

const API_URL = 'https://api.example.com/v1';
const CACHE_DURATION_MS = 5 * 60 * 1000;

async function fill(entity) {
  const memberId = entity['id.memberId'];
  if (!memberId) {
    return false;
  }

  const apiKey = await getSecret('MEMBER-API-KEY');
  if (!apiKey) {
    console.error('memberLookup: secret MEMBER-API-KEY is not defined');
    entity['lookupError'] = 'not-configured';
    return false;
  }

  let response;
  try {
    response = await fetch(`${API_URL}/members/${encodeURIComponent(memberId)}`, {
      Headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
      ThrowOnError: false,
      Cache: { CacheKey: `member-lookup|${memberId}`, DurationInMs: CACHE_DURATION_MS },
    });
  } catch (error) {
    console.error(`memberLookup: request failed - ${error.message}`);
    entity['lookupError'] = 'unreachable';
    return false;
  }

  if (response.StatusCode === 404) {
    return false;
  }
  if (response.StatusCode !== 200) {
    console.warn(`memberLookup: unexpected status ${response.StatusCode}`);
    entity['lookupError'] = 'unavailable';
    return false;
  }

  let member;
  try {
    member = JSON.parse(response.ResponseText);
  } catch (error) {
    console.warn('memberLookup: the response is not valid JSON');
    entity['lookupError'] = 'invalid-response';
    return false;
  }

  entity['points'] = Number(member.points ?? 0);
  entity['tier'] = member.tier ?? 'standard';
  return true;
}

function describe() {
  return {
    identifiers: [{ key: 'memberId' }],
    fields: [
      { path: 'points', type: 'number', description: 'Current points balance' },
      { path: 'tier', description: 'Membership tier' },
      { path: 'lookupError', description: 'Why no data was found, when the lookup failed' },
    ],
  };
}

export default function (context) {
  context.register('runtime.scriptable.passDataProvider.memberLookup', {
    Fill: fill,
    Describe: describe,
  });
}
```

The script is built around a few deliberate choices.

The handler is `Fill` and is declared `async`: the platform calls it by that exact name and awaits it. `Fill` returns `true` when the script found data for the pass and `false` when it found none. The distinction matters because the pass type may list several data providers: the platform runs the providers that found nothing again in a following round, with what the other providers have written so far.

The identifier is read as `entity['id.memberId']`. Identifiers of the pass are always present in the entity under the `id.` prefix. A pass created without `memberId` simply gets nothing from this script.

`fetch` is called with `ThrowOnError: false`. By default `fetch` throws on any non-2xx status, and a throw inside `Fill` makes the whole pass render fail. With the option set to `false`, the script reads `StatusCode` and decides. Network failures still throw whatever the option says, which is why the call is wrapped in `try` / `catch`. The `lookupError` key gives the template a way to show a neutral message when the lookup failed, instead of a wrong value. It has a specific name because a plain `error` key would collide with the same key written by another provider; the namespaced form is `memberLookup.lookupError`.

`Cache` stores the response for five minutes. Only the `CacheKey` identifies the entry, not the URL: the key therefore includes the member id. A fixed key such as `member-lookup` would return the first member's answer to every member. Because responses are cached even when they are errors (`ThrowOnError: false`), the duration should be short enough that an outage does not linger on passes. The details are in [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md).

`Describe` is optional and synchronous. It runs whenever the platform needs the script's namespace and fields: in the pass template editor, when the configuration is saved, and on every pass build. It must therefore be cheap and must not call `fetch`. It tells the admin console which identifiers the script reads and which variables it writes, so that the pass template editor can list them with their descriptions before any pass exists. Its object uses camelCase names, listed in the [Describe table](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md#describe).

{% hint style="info" %}
`Describe` can also return `namespace`. Without it, the script id is the namespace. A namespace must be made of letters, digits and underscores separated by dots, must not start a segment with a digit, and must not be one the platform or a published provider already uses. Saving the configuration reports a clear message when it is not acceptable.
{% endhint %}

## Step 3: wire the script in the pass type

A script that is only registered is never called by a pass: the pass type has to name it. The pass types are stored one per file in `server/passes/<passType>.yml`, and the list of data providers sits at the top level of that file, beside keys such as `kind` and `resources`.

```yaml
dataProviders:
  - provider: script
    scriptId: memberLookup
```

`provider: script` means that the entry runs a tenant script, and `scriptId` is the last part of the registration key. When the pass template editor of the admin console is used instead of YAML, the same entry is added from the **Data providers** section, where the tenant scripts that registered a pass data provider are offered under **Tenant scripts**.

Several entries can be listed; they run in rounds, as described in [Pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md#the-dataproviders-rounds).

Templates read the values under the namespace: `memberLookup.points` and `memberLookup.tier`. The unprefixed names `points` and `tier` are published as well, and the namespaced form is the one recommended in new templates, because another provider can later write the same short key. Identifiers (`id.*`) and `debug.*` keys are never prefixed.

## Step 4: save and check

Saving the advanced configuration runs the script loader: every file is parsed, its top-level code is run, and its default export is called. A syntax error is reported at once, with the file name. Saving also validates the `dataProviders` entries of each pass type: an entry without `scriptId`, or a namespace that is not acceptable, is reported with the file, the entry position and the member at fault, for example `server/passes/loyalty.yml: dataProviders[0].scriptId: ...`.

{% hint style="warning" %}
Saving does not check that a `scriptId` has a registered script behind it, nor that the registered script has the handlers the platform needs. A script id with no matching registration counts as a provider that found data and wrote nothing, with no error (see [Handlers](https://docs.thewalletcrew.io/developers-guides/scripting/handlers.md#comparison-of-the-endpoints)). The check below is therefore always needed.
{% endhint %}

To verify the result on a real pass:

1. Open a pass of that pass type that carries a `memberId` identifier, then its data page (**View data**). The page lists each data provider with its outcome (found, found nothing, failed), its duration and the variables it wrote. **Refresh data** runs the providers again.
2. A provider shown as failed carries the reason, such as **The tenant script failed.** The script threw: a handler is missing or misspelled, or the script raised an error.
3. A provider that found nothing means `Fill` returned `false`: the identifier is missing, the member does not exist, or the lookup failed softly (look for the `lookupError` variable).
4. The pass template editor, in the **Data providers** section, lists the variables declared by `Describe`, and the preview can show real values for a chosen pass.

If the values appear on the data page but not on the pass, the template does not read them yet: add `memberLookup.points` to a field of the pass type.

## Why it never runs

When the data page shows nothing for the script, see [Troubleshooting](https://docs.thewalletcrew.io/developers-guides/scripting/troubleshooting.md#the-script-is-never-called): the usual causes are a `scriptId` that differs from the registration key, a handler not named exactly `Fill`, or a JavaScript error in any file of the tenant.

## Next steps

The same file can grow in several directions. A pass often needs a second provider, for example one that adds the store the member is attached to; the entries then run in rounds. A script that must act when a customer enrols is a [customer pipeline element](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/customer-pipeline-element.md). A script that must choose the pass type is a [pass updater](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-updater.md). [Recipes](https://docs.thewalletcrew.io/developers-guides/scripting/recipes.md) shows these patterns, and [Best practices](https://docs.thewalletcrew.io/developers-guides/scripting/best-practices.md) lists what to review before production.

## FAQ

<details>

<summary><strong>Can a value be written for the pass without an external call?</strong></summary>

Yes. `Fill` can compute values from the identifiers alone, such as a segment label; no `fetch` is needed. [Recipes](https://docs.thewalletcrew.io/developers-guides/scripting/recipes.md) includes such a case.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/first-script.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
