# Galon Functions

> Run JavaScript at a public HTTPS address: upload an ES module, deploy it, call it.

## Before you start

- A Galon account, a project and a prepaid balance. From the console, no key: open Functions, pick a template, select Deploy function — the function is live at its address. From the API below: a key with `functions:deploy` and `job:read`; the `environment` of a deploy must be the key's (`test` with a test key).

## Quickstart

Every example reads `GALON_API_BASE` (`https://api.galon.ai/v1`) and `GALON_API_KEY` from the environment and prints the HTTP status and the JSON body.

**1. Set your key.** Export the base URL and your key.

**curl**

```bash
export GALON_API_BASE="https://api.galon.ai/v1"
export GALON_API_KEY="gln_test_..."
```

**2. Upload the code.** An ES module with `export default { fetch }`, sent as `application/javascript`. The answer gives `source.source_ref` and `source.source_sha256`.

**curl**

```bash
cat > worker.js <<'JS'
export default {
  async fetch(request) {
    return new Response("Hello from Galon Functions");
  },
};
JS
curl -sS -X POST "$GALON_API_BASE/functions/sources" \
  -H "Authorization: Bearer $GALON_API_KEY" \
  -H "Content-Type: application/javascript" \
  --data-binary @worker.js \
  -w '\n%{http_code}\n'
```

**Python 3 (standard library)**

```python
import json, os, urllib.error, urllib.request

source = b"""export default {
  async fetch(request) {
    return new Response("Hello from Galon Functions");
  },
};
"""
req = urllib.request.Request(os.environ["GALON_API_BASE"] + "/functions/sources", data=source, method="POST",
                             headers={"Authorization": "Bearer " + os.environ["GALON_API_KEY"],
                                      "Content-Type": "application/javascript"})
try:
    with urllib.request.urlopen(req) as res:
        print(res.status, json.load(res))
except urllib.error.HTTPError as err:
    print(err.code, json.load(err))
```

**Node.js 18+ (fetch)**

```js
const source = "export default {\n  async fetch(request) {\n    return new Response(\"Hello from Galon Functions\");\n  },\n};\n";
const res = await fetch(`${process.env.GALON_API_BASE}/functions/sources`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.GALON_API_KEY}`, "Content-Type": "application/javascript" },
  body: source,
});
console.log(res.status, JSON.stringify(await res.json()));
```

**3. Deploy it.** `name`: lowercase, up to 40 characters. The answer is `202` with the deploy `job` and the function's public `url`.

**curl**

```bash
curl -sS -X POST "$GALON_API_BASE/functions/deployments" \
  -H "Authorization: Bearer $GALON_API_KEY" \
  -H "Idempotency-Key: quickstart-function-0001" \
  -H "Content-Type: application/json" \
  -d '{"name": "hello", "source_ref": "'"$GALON_SOURCE_REF"'", "source_sha256": "'"$GALON_SOURCE_SHA256"'", "environment": "test", "compatibility_date": "2026-11-01"}' \
  -w '\n%{http_code}\n'
```

**Python 3 (standard library)**

```python
import json, os, urllib.error, urllib.request

req = urllib.request.Request(
    os.environ["GALON_API_BASE"] + "/functions/deployments",
    data=json.dumps({"name": "hello", "source_ref": os.environ["GALON_SOURCE_REF"], "source_sha256": os.environ["GALON_SOURCE_SHA256"], "environment": "test", "compatibility_date": "2026-11-01"}).encode(),
    headers={"Authorization": "Bearer " + os.environ["GALON_API_KEY"],
             "Idempotency-Key": "quickstart-function-0001",
             "Content-Type": "application/json"},
    method="POST",
)
try:
    with urllib.request.urlopen(req) as res:
        print(res.status, json.load(res))
except urllib.error.HTTPError as err:  # the error body carries detail.code and detail.next_action
    print(err.code, json.load(err))
```

**Node.js 18+ (fetch)**

```js
const res = await fetch(`${process.env.GALON_API_BASE}/functions/deployments`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.GALON_API_KEY}`, "Idempotency-Key": "quickstart-function-0001", "Content-Type": "application/json" },
  body: JSON.stringify({name: "hello", source_ref: process.env.GALON_SOURCE_REF, source_sha256: process.env.GALON_SOURCE_SHA256, environment: "test", compatibility_date: "2026-11-01"}),
});
console.log(res.status, JSON.stringify(await res.json()));
```

**4. Wait for the deploy.** Read the job until `status` is final.

**curl**

```bash
curl -sS -X GET "$GALON_API_BASE/functions/jobs/${GALON_FUNCTION_JOB_ID}" \
  -H "Authorization: Bearer $GALON_API_KEY" \
  -w '\n%{http_code}\n'
```

**Python 3 (standard library)**

```python
import json, os, urllib.error, urllib.request

req = urllib.request.Request(
    os.environ["GALON_API_BASE"] + "/functions/jobs/" + os.environ["GALON_FUNCTION_JOB_ID"],
    headers={"Authorization": "Bearer " + os.environ["GALON_API_KEY"]},
    method="GET",
)
try:
    with urllib.request.urlopen(req) as res:
        print(res.status, json.load(res))
except urllib.error.HTTPError as err:  # the error body carries detail.code and detail.next_action
    print(err.code, json.load(err))
```

**Node.js 18+ (fetch)**

```js
const res = await fetch(`${process.env.GALON_API_BASE}/functions/jobs/${process.env.GALON_FUNCTION_JOB_ID}`, {
  method: "GET",
  headers: { Authorization: `Bearer ${process.env.GALON_API_KEY}` },
});
console.log(res.status, JSON.stringify(await res.json()));
```

**5. Call your function.** The function answers on its own public HTTPS address; no key is needed.

**curl**

```bash
curl -sS "$GALON_FUNCTION_URL" -w '\n%{http_code}\n'
```

## Concepts

**Module format.** An ES module whose default export has `fetch(request, env, ctx)`. Service-worker scripts and WebAssembly are refused.

**Sources, then deploys.** `POST /v1/functions/sources` stores the code and returns its reference; `POST /v1/functions/deployments` deploys a reference under a name; `POST /v1/functions/deletions` removes a revision.

**Pricing on the API.** `GET /v1/functions/pricing` returns the current price per million requests and per million CPU milliseconds, in USD.

**Outbound requests.** A function calls public websites over HTTPS on port 443, by host name. IP addresses, private networks, credentials in the URL and other ports (25 included) are refused.

**Variables and secrets.** The variables and secrets of your project's environment (Project → Variables) reach your functions as `env.NAME` — `fetch(request, env, ctx)`. A secret never appears in a revision or a log; deploy again after a change so the new values are taken.

**Revisions and rollback.** Each deployment is a revision. In the console, roll back to any earlier one in one click: a new deployment of that code, same address.

## API reference

These routes are served by the code but are not in the OpenAPI contract yet:

| Method | Path | Auth | What it does |
|---|---|---|---|
| GET | `/v1/functions/pricing` | key `job:read` | Current prices in USD |
| POST | `/v1/functions/sources` | key `functions:deploy` | Upload an ES module |
| POST | `/v1/functions/deployments` | key `functions:deploy` | Deploy a source under a name |
| POST | `/v1/functions/deletions` | key `functions:deploy` | Delete a revision |
| GET | `/v1/functions/jobs/{job_id}` | key `job:read` | Read a deploy or delete job |

## Errors

Every error is JSON: `{"detail": {"code", "message", "next_action"}}`. `next_action.code` is stable, `next_action.hint` says what to do next, and `console_url` is added when a person must act. The codes below are those this service returns.

| Status | Code | When | next_action |
|---|---|---|---|
| 413 | `functions_request_too_large` | The request body is over the limit (10 MiB). | `fix_request` |
| 504 | `functions_timeout` | The function ran past its time limit (30 s); the container was restarted. | `retry_later` |
| 402 | `functions_account_blocked` | The project's balance is used up: invocations are refused until a top-up. | `top_up_balance` |
| 401 | `api_key_invalid` | No key, or an unknown, revoked or expired key. | `use_valid_api_key` |
| 403 | `scope_missing` | The key lacks `functions:deploy` or `job:read`. | `add_missing_scope` |
| 403 | `functions_tenant_not_allowed` | Functions is not open to this account. | `check_project_access` |
| 400 | `idempotency_key_required` | No `Idempotency-Key` on a deploy. | `fix_request` |
| 415 | `functions_module_not_js` | The source is not sent as JavaScript. | `fix_request` |
| 422 | `functions_module_not_js` | The content is not an ES module with a default export. | `fix_request` |
| 413 | `functions_module_too_large` | The script is over the size limit. | `fix_request` |
| 422 | `functions_name_invalid` | The name does not match `[a-z][a-z0-9-]{0,39}`. | `fix_request` |
| 403 | `functions_environment_mismatch` | `environment` differs from the key's. | `use_key_of_right_environment` |
| 402 | `functions_balance_exhausted` | The prepaid balance is used up. | `top_up_balance` |
| 409 | `functions_operation_in_progress` | Another deploy of this function is running. | `resolve_conflict` |
| 503 | `functions_temporarily_unavailable` | Temporary: retry with the same Idempotency-Key. | `retry_later` |

| next_action | What to do |
|---|---|
| `fix_request` | The request is invalid. Fix it as 'message' and 'field' say, using the OpenAPI contract, then send it again. Do not retry it unchanged. |
| `retry_later` | Temporary error on Galon's side. Retry with exponential backoff and the same Idempotency-Key; if it lasts, contact support with the X-Request-Id header. |
| `top_up_balance` | The project balance does not cover this call. Top up the balance in USD in the console, then retry with the same Idempotency-Key. |
| `use_valid_api_key` | Send a valid Galon API key as 'Authorization: Bearer <key>'. If the key was revoked or has expired, create a new one in the console and retry with it. |
| `add_missing_scope` | This key does not have the scope this call needs. Create a key with that scope in the console, then retry the same call with the new key. |
| `check_project_access` | This project or key is not allowed to do this. Its owner must review the project, its key and its account in the console. |
| `use_key_of_right_environment` | This call is not allowed for this key's environment (test or live). Use a key of the other environment, created in the console. |
| `resolve_conflict` | The request conflicts with the resource state or with an earlier request under the same Idempotency-Key. Read the resource first; for a new intent, use a new Idempotency-Key. |

## Limits, free tier and pricing

Read from the platform code each time this page is served.

| Limit | Value |
|---|---|
| Script size (default) | **1 MiB** |
| Request body (max) | **10 MiB** |
| Variables and secrets per environment | **100** |
| Variable value (max) | **4 KiB** |
| Secret value (max) | **8 KiB** |

Usage prices, in US dollars, read from the price grid served by the platform each time this page is served. Paid from the prepaid balance.

| Item | Price | Unit |
|---|---|---|
| `requests` | 0.0253 USD | per million requests |
| `cpu_ms` | 0.011528 USD | per million CPU-ms |

Functions are paid per request and per CPU millisecond from the prepaid balance; `GET /v1/functions/pricing` returns the prices in force.

## FAQ

**How am I billed?**

Per request and per CPU millisecond, at the public prices, from the project's prepaid balance, settled every hour; nothing is billed when nothing runs.

**Can I bring existing `fetch` handler code?**

Modules with `export default { fetch }` run as they are.

**Do I need a key to call my function?**

No: the function's address is public. Protect it in your code if needed.

**Do I need a key to deploy from the console?**

No: the console deploys under your session (an administrator of the project). Keys are for your code and your AI agents.

**How do I give a secret to a function?**

Add it to your project's variables as a secret, then deploy the function again: it reads `env.NAME`. Keep secrets out of the code.

## More

- [Authentication](/cloud/docs/platform/authentication)
- [Projects: live and test](/cloud/docs/platform/environments)
- [Prepaid balance](/cloud/docs/platform/balance)
- [Quotas and rate limits](/cloud/docs/platform/quotas)
- [Terms of Service](/legal/terms-of-service)
- [Acceptable Use Policy](/legal/acceptable-use-policy)
- [Privacy Policy](/legal/privacy-policy)
- [Refunds and prepaid balance](/legal/prepaid-balance-and-refund-policy)
- [Legal Notice](/legal/legal-notice)
- [All legal documents](/legal)
