Serverless Functions
Serverless functions
A serverless function is a handler you write that Ngris wraps in a base runtime image and runs scale-to-zero. It sits idle at zero instances, cold-starts on the first request, then scales back to zero after an idle window (unless you set it to stay warm). There is no server to keep alive, no port to bind, and no Dockerfile to write: you ship a function, Ngris runs it.
A function is a fifth application type (function), alongside static, managed, fullstack, and wordpress. Like a managed backend it carries a runtime and is served in-cluster through a managed endpoint — the difference is that it runs at min_replicas=0 and the edge wakes it on demand.
Serverless functions require the functions_enabled entitlement — the on/off master gate. Without it, create returns 403 Serverless functions are not available on your plan. Your plan also sets a per-account max_functions quota (how many function apps you can hold at once); reaching it returns 403 Function limit reached.
Serverless function
DeployedYour handler runs in an isolated sandbox that scales to zero when idle (unless it is set to stay warm) and cold-starts on the first request.
- Runtime
- nodejs24
- Handler
- index.mjs:default
- Idle timeout
- 300s
- Request timeout
- 30s
- Max concurrency
- 40 req/instance
Function or managed backend?
Both run your code in the same isolated sandbox; the difference is how they run and what you write.
- Reach for a function for event and HTTP handlers and spiky or low-traffic workloads — a webhook receiver, a small API, a cron-style task hit occasionally — where nothing needs to run between requests and a cold start on the first request after idle is acceptable. You write a handler; Ngris supplies the server.
- Reach for a managed backend for an always-on service, long-lived streaming responses (SSE), steady traffic, or anything where you want a full container /
Dockerfileand control over the port and process. It stays up and answers every request with no cold start.
You are not locked in: a function and a backend are both just application types, so you can start with a function and move to a managed backend (or a full-stack app) later if the workload grows into an always-on service.
The handler contract
Your handler is an ES module whose default export is a Web Fetch-style handler — it receives a standard Request and returns a Response (or a Promise of one). If you have written a Cloudflare Worker, a Deno handler, or a Next.js route, this is the same shape. The runtime wrapper loads it with a dynamic import(), so your entry file must be a genuine ES module — see the ESM note below.
// index.mjs
export default async function (request) {
const url = new URL(request.url);
return new Response(JSON.stringify({ hello: "world", path: url.pathname }), {
headers: { "content-type": "application/json" },
});
}
By default Ngris loads the default export of index.js at the root of your source. Point somewhere else with the handler setting (function_handler), written as <file>:<export> — e.g. api/webhook.mjs:handler for the handler export of api/webhook.mjs. The default is index.js:default.
8080 and answers a platform health endpoint at /_ngris/health for you. Unlike a managed backend, you never set a listen port or a health-check path — the wrapper owns both. A function also serves every path (no backend paths) and Ngris runs its instance for you (no replica counts): a request to change its port, backend paths or replicas is refused. Just write the handler.
index.js:default.ESM is required (name it .mjs, or set type: module)
The wrapper loads your handler with an ESM dynamic import(), so the entry file must be a real ES module — a plain index.js with export default is treated as CommonJS and the build fails to load it. Node decides module vs. script from the file extension and the nearest package.json, so pick one of:
- Name the file
index.mjs(and set the handler toindex.mjs:default). A.mjsfile is always an ES module regardless of anypackage.json— the simplest, zero-config choice. - Or keep
index.jsand add"type": "module"to yourpackage.json. That makes every.jsin the project an ES module, soindex.js:default(the built-in default handler) then loads correctly.
SyntaxError: Unexpected token 'export' or failed to load handler index.js:default. Fix it by renaming to index.mjs (and updating function_handler) or adding "type": "module".
npm dependencies
Functions use npm packages the normal Node way. Include a package.json at your source root (a package-lock.json is optional but recommended); the build installs your production dependencies and bundles the resulting node_modules into the function image, so anything you import is present at runtime.
- With a lockfile the build runs
npm ci --omit=dev(reproducible); without one it falls back tonpm install --omit=dev. Either way devDependencies are skipped — put anything the handler needs at runtime independencies. - Ship source, not
node_modules— the build installs a clean tree inside the sandbox. Leaving a stalenode_modulesin your.ziponly makes it larger.
For example, importing a small dependency just works — import { nanoid } from "nanoid"; in your handler, with nanoid listed under dependencies, is installed at build time and available on every request.
{
"name": "my-fn",
"type": "module",
"dependencies": { "nanoid": "^5.0.0" }
}
index.html at its root (or set a publish dir later). Optional — you can also upload after creating.Runtimes
Pick the base runtime your handler wraps into. The supported runtimes today:
| Runtime | What it is |
|---|---|
| nodejs24 | Node.js 24 LTS. The default if you don’t choose one. nodejs20 and nodejs22 are still accepted and run on Node.js 24. |
Set the runtime as function_runtime at create time. An unsupported value returns 400 unsupported function_runtime (supported: nodejs24; nodejs20 and nodejs22 are accepted as aliases for it).
curl -X POST "https://api.ngris.com/v1/applications" \
-H "X-API-KEY: <your_api_key>" \
-H "Content-Type: application/json" \
-d '{
"name": "my-fn",
"type": "function",
"source": "upload",
"function_runtime": "nodejs24"
}'Config knobs
Every knob is optional — the defaults give sane cold-start behaviour, so a bare create just works. Set them at create time, or change them later on the app’s Settings page (Idle time, Request timeout, Max concurrency, plus CPU and memory) or with PUT /v1/applications/{uuid}/runtime.
| Setting | Default | What it does |
|---|---|---|
| function_idle_seconds | 300 | Scale to zero after this many idle seconds with no traffic. Set 0 to never scale down (stays warm — no cold starts, but you keep an instance up). Range 0–3600. |
| function_timeout_seconds | 30 | Per-request wall-clock cap, enforced at the edge — a single invocation that runs longer is cut off. Range 1–300. |
| function_max_concurrency | 40 | Concurrent requests the function handles at once. A function runs as one instance; past this limit, a request waits at the edge for a free slot, first come, first served (see How requests work). Range 1–200. |
How requests work
A function’s whole life cycle is driven by traffic:
- First request (cold start). With no instance running, the edge cold-starts one (0 → 1) and holds the request until the instance is ready, then proxies it through. Requests that arrive while it starts wait for that same start, then go through. That first request waits for the instance to start, so it is slower than the rest.
- Subsequent requests (warm). While the instance is up, requests reuse it directly, with no cold start.
- A busy function. A function doesn't scale out: it handles up to
function_max_concurrencyrequests at once. Past that, a request waits at the edge for a free slot, and the waiting requests are served in the order they arrived. - The wait has a cap. If the function stays busy, or more requests arrive than the edge can hold for it, the visitor gets an error page (
503with aRetry-Afterheader) that asks them to try again in a few moments. If you set your own Service Unavailable page under Error Pages, visitors see that one. - Visitors who leave. A visitor who closes the connection while waiting drops out of the line, and a start already under way goes on for everyone else.
- Health checks don’t wake it. An uptime check of a sleeping function shows Asleep, counts as up, and leaves the function asleep.
- Idle (scale to zero). After
function_idle_secondswith no traffic, Ngris scales the function back to zero. Nothing runs until the next request wakes it again.
This is the trade you are opting into: nothing running between requests, in exchange for a cold start on the first request after idle. If cold starts hurt your workload, set function_idle_seconds=0 to keep an instance warm, or use an always-on managed backend instead. If your function is often busy, raise Max concurrency on the app’s Settings page so fewer requests wait.
How it works
- Deploy a handler (upload a
.zipor connect Git) — ngris wraps it in the runtime image. - The first request cold-starts an instance; later requests reuse the warm one.
- After the idle time with no traffic, it scales back to zero. An idle time of 0 keeps it warm: it never scales to zero.
- Set env vars on the Environment page; releases are on Deploys.
Uptime
Checked from our network. Your visitors' sign-in and firewall rules don't block the check, and checks never count toward your usage. Asleep: this function is idle and wakes on the next visit.
| Endpoint | Status | 24 h | 7 d | Last check | Settings |
|---|---|---|---|---|---|
| acme-contact-form.ngris.dev | Asleep | 100% | 100% | 2m ago |
Environment variables, deploys, logs & previews
Everything you already know from the other app types works the same way for a function — there is nothing function-specific to learn here.
- Environment variables & secrets are set under the app’s Environment page (or the env API) and injected into the running instance under their exact names; mark sensitive values as Secret (write-only: never shown again). Read them the normal Node way —
process.env.MY_TOKEN. See Environment variables & secrets. - Outbound network access is off by default: a function can resolve DNS and reach the databases connected to it, nothing else. On a paid plan, set
NGRIS_EGRESS_HTTPS=onto let it call public HTTP/HTTPS endpoints (TCP 80/443, public IPv4 only). See Outbound network access. - Deploys upload a
.zipor push to a connected git repo, then move throughqueued→building→image_ready→rolling_out→ready, exactly like a backend deploy. - Build logs tail live under the deploy’s Build log — watch
npm ciand the handler-wrap run, and see exactly why a build broke. - Preview URLs (
<deploy-uuid>.<plan-domain>) work as for other apps and follow the protections of the function's main endpoint, but a function's preview URL reaches the version that is live now, not the deploy it belongs to. A new version is checked before it goes live: it must start and pass its health check, or the deploy fails and the live version keeps serving. - No web analytics. A function is an API, so web analytics count no pageviews for it.
NGRIS_APP_ENV_*. Each variable can target Production, Preview deploys, or Both. Secrets are never shown again — to change one, enter a new value. Saving a change applies it right away: a running managed app rolls to pick it up.
Add variable
| Name | Value | Type |
|---|---|---|
| MY_TOKEN | •••••••• | secret |
| NGRIS_EGRESS_HTTPS | on | plain |
Deploy a function
Dashboard walkthrough
- Create the app. Open Applications → New Application and pick type Serverless function.
- Pick a runtime & handler. Choose a runtime (
nodejs24) and, if your entry point isn’tindex.js:default, set the handler (e.g.index.mjs:default). Tune idle, request timeout, and concurrency if the defaults don’t fit — or leave them. - Set env vars & secrets. Add config and tokens under Environment, marking sensitive values as Secret.
- Upload or connect. Drop a
.zipwith your handler at the root (a genuine ES module —index.mjs, orindex.jswith"type":"module"), plus apackage.jsonif you have dependencies, or connect a Git repo so every push redeploys. - Watch the build. Open the deploy’s Build log — it tails live — and wait for the deploy to reach
ready. - It’s live. Ngris created the function’s endpoint when you created the app (a generated hostname, shown on the app page); it starts serving once this first deploy is
ready. Hit its URL — the first request cold-starts your function — and add a custom domain whenever you like; TLS is provisioned for you.
API — create a function
curl -X POST "https://api.ngris.com/v1/applications" \
-H "X-API-KEY: <your_api_key>" \
-H "Content-Type: application/json" \
-d '{
"name": "my-fn",
"type": "function",
"source": "upload",
"function_runtime": "nodejs24",
"function_handler": "index.mjs:default",
"function_idle_seconds": 300,
"function_timeout_seconds": 30,
"function_max_concurrency": 40
}'
Only name and type are required — every function_* field is optional and defaults as above. Use "source":"git" with a repo_url to connect a repo instead of uploading.
The function’s endpoint is created with it: the 201 response includes the new endpoint and its url. If your plan’s endpoint limit is already reached, the function is still created — the response is 207 with endpoint_error instead — and you add an endpoint once there’s room (POST /v1/endpoints with "serving_mode":"managed" and the function’s application_uuid).
API — upload the handler & deploy
curl -X POST "https://api.ngris.com/v1/applications/{uuid}/deploys" \
-H "X-API-KEY: <your_api_key>" \
-F "file=@my-fn-src.zip" \
-F "version=v1.0.0" # optional label
The build runs asynchronously — it wraps your handler in the base runtime image, installs your dependencies, and produces the signed, digest-pinned image. Poll GET /v1/applications/{uuid}/deploys until the newest deploy reaches ready, or stream the build log with GET /v1/applications/{uuid}/deploys/{deploy_uuid}/logs. The function’s endpoint then serves it; add a custom domain exactly like any other app.
Deploy a new version
Drag a .zip of your app here, or click to browse
Your source is built into a signed, scanned container image.
SyntaxError: Unexpected token 'export' — rename to index.mjs or set "type":"module"), a missing dependency, a handler path that doesn’t resolve (check function_handler points at a real <file>:<export>), or a handler that throws on start. Walk the fixes in Deploy troubleshooting.
See the build log for the full output.