> 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/best-practices.md).

# Best practices

Rules for writing and reviewing scripts: secrets, retries, caching, soft failure, logging, registration, naming, testing and review before production.

A script shares a tenant with every other script: an error in one file can make all of them fail, a slow remote call slows the pass render that waits for it, and a secret written in a file is visible to everyone who can read the configuration. The practices below come from the mistakes seen most often in real scripts, and each one is stated with its reason so that it can be applied to cases not listed. They double as a review checklist at the end of the page.

<details>

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

* A script with an API key written inline: the key is in the configuration history forever, and has to be rotated.
* A lookup `fetch` with no cache: every render of a pass calls the CRM again.
* A `Fill` that throws when the CRM is down: no pass can be displayed during the outage.
* Two files registering the same pass data provider: the one that wins changes with the next edit.

</details>

## Secrets

Credentials are read with `getSecret` from `twc/secrets` and never written in a script or in a YAML file. A secret is managed per tenant in the admin console, can be rotated without editing the script, and has versions that expire. A script that needs a secret treats `null` as "not configured": it logs a short message that names the secret key, not its value, and reports that no data was found. The key rules, the versions and the cache are in [twc/secrets](https://docs.thewalletcrew.io/developers-guides/scripting/modules/secrets.md).

Production URLs and identifiers do not belong in the script either, when the same script is copied between environments. Each environment keeps its own secrets, and a base URL kept in a secret, or the same configuration value read in the same way, lets the file stay identical from the staging tenant to production.

## Calls to other systems

`fetch` throws on any non-2xx status unless `ThrowOnError` is `false`, and it always throws on a network failure. A call whose failure must not break the handler is therefore written with `ThrowOnError: false`, a check of `StatusCode`, a check that the body is not empty before `JSON.parse`, and a `try` / `catch` around the call. The status test is written positively (`=== 200`, or `>= 200 && < 300`), because an inverted test is the most common bug found in reviews. The details of `fetch` are on its [page](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md).

`fetch` retries transient failures for every method, so a `POST` can reach the target more than once: targets that receive a script's `POST` should be idempotent (see [Idempotency](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md#idempotency)). Queries and paths sent to a remote system are built with `encodeURIComponent` or fixed text, never by concatenating text received from a customer or another system.

A script runs inside the request or job that triggered it, so it stays short and light. Loops over large collections are capped, and a cap that is reached is logged, so that a truncated result is visible. A handler that runs more than 5 000 ms before its first `await` is stopped (see [How scripts run](https://docs.thewalletcrew.io/developers-guides/scripting/how-scripts-run.md#time-limits)). Waiting with `sleep` in a loop is a sign that the work belongs to a scheduled job or to the remote system.

## Caching

A value that is read at each pass render and changes rarely is cached with the `Cache` option of `fetch`. Two rules prevent the usual bugs. The `CacheKey` has to contain everything that distinguishes one answer from another, the customer identifier first, because only the key identifies the entry; the URL, the method and the body are not part of it. The duration is as short as the use allows, because with `ThrowOnError: false` an error response is cached for the same duration as a success.

## Soft failure

The right reaction to a failed remote call depends on the extension point, and it is chosen deliberately.

| Extension point                         | Failure handling                                                                                                                                                        |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Pass data provider                      | Catch the failure, write a specific error key (such as `lookupError`), return `false`. A throw fails the pass render, so a CRM outage would stop passes from displaying |
| Pass updater notification               | An error is logged and the operation continues; log a short message with the status                                                                                     |
| Customer pipeline element, email engine | Let the failure reach the caller when skipping the work would leave systems out of step; catch it when the step is optional                                             |
| Push updates                            | A throw in `GetPasses` fails the task; a failure on one row is logged and the others continue                                                                           |

A `Fill` that returns `true` when nothing was found hides the problem on the pass data page and stops other providers from running again. It returns `false` when it found nothing.

## One key, one file

Every registration key is registered in exactly one file (see [How scripts run](https://docs.thewalletcrew.io/developers-guides/scripting/how-scripts-run.md#one-key-one-file)). Every script id used in YAML (`scriptId`, `scriptName`) matches the last segment of a registration key exactly, including case. A handler is registered under the exact method name, in PascalCase, and every returned object uses the casing documented for its shape. These are the three alignments that, when broken, fail without an error message; a short review of them catches most problems before they reach production.

## Writing the code

Scripts stay small and readable, because there is no way to share code between files and because they are reviewed by people who did not write them.

* Variables are declared with `const` or `let`; an undeclared variable creates a global.
* Lookup tables are kept in one file. A table duplicated in several files drifts, and the files then disagree.
* A value that is computed once is not recomputed at each handler call; constants sit at the top of the file, where the top-level code must stay fast (see [How scripts run](https://docs.thewalletcrew.io/developers-guides/scripting/how-scripts-run.md#time-limits)).
* Dead code and commented-out code are deleted. Comments explain a constraint that is not obvious from the code, for example an unusual format required by a remote system, and not the history of the file; the configuration history keeps that.
* Dates are returned as ISO 8601 strings with an offset (see [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md#dates)).
* Truthiness is not relied on for consents and flags that may arrive as text. `'n'` is truthy. A small `toBoolean` function states what each accepted text means, and the mapping between a boolean and a remote enumeration is written once, as in recipe 4 of the [recipes](https://docs.thewalletcrew.io/developers-guides/scripting/recipes.md). A `consents_*` value may arrive as a boolean or as text, depending on the form (see [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md#key-conventions)).
* Only the values the pass or the next step needs are written on the entity. Whole API responses are not stored in `debug.*` keys.
* The pass is changed by returning the new value from the hook, not by calling the platform's own REST API from the script.

## Logging

`console.log`, `console.debug` and `console.table` write at Debug level, which the default production configuration does not record (see [Utility globals](https://docs.thewalletcrew.io/developers-guides/scripting/globals/tools.md#console)), so `console.info`, `console.warn` and `console.error` are the useful levels. A message says what happened and which step it was, and carries a status code or an identifier of the object when that helps. It never carries a secret, a token, an email address, a phone number or a payload received from a customer.

## Naming

Script ids describe the capability they provide, in camel case: `memberLookup`, `crmContact`, `memberSync`. For a pass data provider the id doubles as the namespace, so a hyphen (`crm-data`) needs a `namespace` returned by `Describe`. The file is named after the id (`server/scripts/memberLookup.js`). Names such as `script1`, `test` and `new` are avoided because they say nothing when they appear in a pass type or a scheduler task a year later. Old names that exist in the configuration are left as they are.

## Testing

Scripts are tested in a non-production tenant first, by exercising the real path: a pass data provider is checked on the pass data page of a pass (or with `GET /api/{tenantId}/passes/{passId}/data`), a connector script in its slot editor and then on a test pass, a flow step by enrolling a test customer, a pass updater hook by creating, updating and installing a test pass, a push update by running its scheduler task on a small list, an email engine by sending a test email. Saving only checks that the files load (see [How scripts run](https://docs.thewalletcrew.io/developers-guides/scripting/how-scripts-run.md#validation-when-saving)). For each script, the unhappy paths are exercised once as well: the remote system answers with an error, the identifier is missing, the secret is absent.

Once the staging tenant behaves, the files are copied to production in one change, with the pass type, flow or scheduler wiring that references them, and the first real execution is watched.

## Reviewing a change

The checklist below is applied to every script change, whoever wrote it.

| Check        | What to look for                                                                                                                     |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| Registration | The key is registered in one file; the `scriptId` matches; the handler names are exact                                               |
| Secrets      | No credential inline; `getSecret` result checked for `null`                                                                          |
| Failure      | `ThrowOnError: false` where the handler must survive; status checked; JSON parsed only after a check; `try` / `catch` around `fetch` |
| Return       | Casing of the returned keys; `Fill` returns a boolean on every path; hooks return `null` consistently                                |
| Cache        | The key contains the identifier; the duration is short                                                                               |
| Retries      | A `POST` target is idempotent                                                                                                        |
| Logs         | No secret or personal data; useful levels only                                                                                       |
| Hygiene      | No dead or commented-out code, no undeclared variable, no duplicated table                                                           |
| Wiring       | Pass type, flow, scheduler or email configuration updated together with the script                                                   |


---

# 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/best-practices.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.
