Node.js
Write a Coderunner Function, Job or Schedule in Node.js.
Use this reference for Functions, Jobs and Schedules written in Node.js. For a container with your own web server, see Services.
Project files
my-function/
├── handler.js
└── package.jsonZip these at the root of the archive, not inside a folder.
{
"name": "my-function",
"version": "1.0.0",
"main": "handler.js",
"scripts": { "start": "node handler.js" },
"dependencies": {}
}The start script is only needed for a Service, which runs its own server. Functions, Jobs and Schedules call your handler and never run npm start, so you don't write a server or listen on a port. Add npm packages under dependencies as usual. fetch is built in.
The handler
Export a function named handler:
const handler = async (context, payload) => {
// your code
};
module.exports = { handler };payloadis the JSON input: the request body for a Function, the run's input for a Job.contextis reserved for information from the runtime. Don't rely on its contents yet.
module.exports is the convention in these docs. An ES module export, export async function handler(context, payload), works too.
Function example
A Function can return anything. This shape is the convention:
const handler = async (context, payload) => {
if (!payload?.name) {
return {
statusCode: 400,
body: { error: "name is required" },
headers: { "content-type": "application/json" },
};
}
return {
statusCode: 200,
body: { greeting: `Hello, ${payload.name}` },
headers: { "content-type": "application/json" },
};
};
module.exports = { handler };statusCode | Use it for |
|---|---|
200 / 201 | Success / something was created |
400 | Missing or invalid input |
401 / 403 | Not signed in / not allowed |
404 | Not found |
500 | Something unexpected went wrong. Don't put error internals in the body |
Job and Schedule example
A Job or Schedule doesn't need to return anything:
const handler = async (context, payload) => {
console.log("Import started");
const count = await importCustomers(payload?.source);
console.log(`Imported ${count} customers`);
};
module.exports = { handler };If an error escapes the handler, the run is marked Failed. If you catch it, the run succeeds and handling it is up to you. See Jobs.
Settings, secrets and logs
- Read settings with
process.env.NAME. See Configuration and secrets. - Read secrets from the Secrets API at runtime, never from your ZIP. A ready-to-use helper is in Configuration and secrets.
console.logandconsole.errorgo to the Process Log.
Deploy
gf deploy --name my-function --workload-type function # or job, or schedule with --scheduleThe CLI detects Node.js from package.json. Or create the Coderunner in the Client Portal and upload the ZIP; see Functions.