Sub topic 4
Writing a JavaScript action
This chapter assumes you can read basic workflow syntax (jobs, steps, uses, with) and write JavaScript that runs on Node with npm. You also need to know basic Git commits and branches. The chapter builds a small JavaScript action from scratch and explains what the runner does with it. Bundling, the toolkit packages, and releasing get their own chapters, so they appear here only where the example needs them.
What a JavaScript action is
A JavaScript action is a repository, or a folder inside one, that contains an action.yml file and a script. The runner starts the script directly on the runner machine with a Node runtime that GitHub provides. No container is involved.
This has three consequences:
- Fast start. There is no image to build or pull, so the action begins almost immediately.
- Cross-platform. The same action can run on Linux, macOS, and Windows runners, because Node runs on all of them.
- Shared environment. The action sees the same filesystem, tools, and environment variables as the other steps in the job.
The cost is that you depend on the Node version the runner offers, and your dependencies must be present when the script starts.
Project layout
A minimal action needs three files at the repository root:
hello-action/
action.yml
index.js
package.jsonCreate package.json and install the two toolkit packages:
npm init -y
npm install @actions/core @actions/githubThese packages end up in node_modules/. The runner does not run npm install for you, so the action will fail with Cannot find module '@actions/core' unless the dependencies ship with the action. The bundling chapter solves this properly. While experimenting, you can commit node_modules/ as a stopgap.
The metadata file
action.yml tells the runner what the action is and how to start it.
name: 'Hello World'
description: 'Greet someone and record the time'
inputs:
who-to-greet:
description: 'Who to greet'
required: true
default: 'World'
outputs:
time:
description: 'The time we greeted you'
runs:
using: 'node20'
main: 'index.js'The runs block is the part specific to JavaScript actions:
usingselects the Node runtime.node20is a supported value. Older values such asnode16are deprecated, and the runner may warn about them or force a newer version.mainis the path to the entry script, relative to the folder that containsaction.yml.
If using names an unsupported runtime, or main points to a file that does not exist, the step fails before any of your code runs.
The entry script
const core = require('@actions/core');
const github = require('@actions/github');
try {
const nameToGreet = core.getInput('who-to-greet');
console.log(`Hello ${nameToGreet}!`);
core.setOutput('time', new Date().toTimeString());
console.log(`Event name: ${github.context.eventName}`);
} catch (error) {
core.setFailed(error.message);
}The script does four things:
core.getInput('who-to-greet')reads the input value.console.logwrites to the step's log.core.setOutput('time', ...)publishes a value that later steps can read.github.context.eventNamereports which event triggered the workflow, such aspushorpull_request.
The catch block calls core.setFailed, which prints the message as an error annotation and marks the step as failed.
What the runner does with your script
Understanding the sequence helps with debugging.
The runner turns each with: value into an environment variable. The name is the input name in uppercase with spaces replaced by underscores, prefixed with INPUT_. Hyphens stay as they are, so who-to-greet becomes INPUT_WHO-TO-GREET. core.getInput reads that variable, so you rarely need to touch it yourself. The name matters when you debug, because you can print process.env and look for it.
Defaults declared in action.yml are applied by the runner before the script starts. A missing optional input with no default arrives as an empty string, not undefined.
Inputs are always strings
Every input arrives as text. The value 'false' is a non-empty string, so if (core.getInput('dry-run')) is true even when the workflow passed false. Use the typed helpers instead:
const core = require('@actions/core');
const dryRun = core.getBooleanInput('dry-run');
const retries = parseInt(core.getInput('retries'), 10);
const files = core.getMultilineInput('files');
console.log({ dryRun, retries, files });getBooleanInputacceptstrue,True,TRUE,false,False, andFALSE, and throws on anything else.getMultilineInputsplits on newlines and returns an array.getInput('name', { required: true })throws if the value is empty, which is useful when the input has no default.
Numbers have no helper. Parse them yourself and check for NaN.
Asynchronous code
Real actions call APIs, so most scripts are asynchronous. Wrap the work in an async function and handle errors in one place:
const core = require('@actions/core');
const github = require('@actions/github');
async function run() {
try {
const token = core.getInput('token', { required: true });
const octokit = github.getOctokit(token);
const { owner, repo } = github.context.repo;
const { data } = await octokit.rest.repos.get({ owner, repo });
core.info(`Default branch: ${data.default_branch}`);
core.setOutput('default-branch', data.default_branch);
} catch (error) {
core.setFailed(error instanceof Error ? error.message : String(error));
}
}
run();Two details matter here. First, the catch block turns a rejected promise into a failed step. Without it, Node 20 treats an unhandled rejection as a fatal error and exits with a non-zero code, but the log shows a raw stack trace instead of a clean message. Second, core.info is the toolkit's equivalent of console.log, and it is the better choice when you also use core.warning and core.error.
The action is called with the token passed in from the workflow, for example with: token: ${{ secrets.GITHUB_TOKEN }}. An action cannot read workflow secrets on its own. Anything it needs must arrive as an input or an environment variable.
Step status and exit codes
The runner decides whether the step passed from the process exit code. core.setFailed sets process.exitCode = 1 and logs the message, but it does not stop your script. Code after the call still runs. Add a return when you want to stop:
const core = require('@actions/core');
function validate(value) {
if (!/^[a-z0-9-]+$/.test(value)) {
core.setFailed(`Invalid name "${value}". Use lowercase letters, digits, and hyphens.`);
return false;
}
return true;
}
const name = core.getInput('name', { required: true });
if (validate(name)) {
core.info(`Name accepted: ${name}`);
}Calling process.exit(1) also fails the step, but it can cut off buffered log output. Prefer setFailed plus an early return.
Testing the action in a workflow
Put the workflow in the same repository. uses: ./ refers to the action at the repository root. The repository must be checked out first, or the runner cannot find action.yml.
name: Test hello action
on: [push]
jobs:
hello:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run the local action
id: hello
uses: ./
with:
who-to-greet: 'Mona'
- name: Show the output
run: echo "The time was ${{ steps.hello.outputs.time }}"The id: hello on the action step is what lets the later step read steps.hello.outputs.time. Without an id, the output is unreachable.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module '@actions/core'` | Dependencies were not committed or bundled | Bundle the action, or commit `node_modules/` while experimenting |
| `Can't find 'action.yml'` | Missing `actions/checkout` before `uses: ./`, or wrong path | Add the checkout step; check the folder in `uses` |
| Input is empty in the script | Name mismatch between `with:` and `getInput`, or the key is missing from `inputs:` | Match the exact spelling, including hyphens |
| `if (getInput('flag'))` is always true | The string `'false'` is truthy | Use `getBooleanInput` |
| Step is green although the work failed | Error caught and logged, but `setFailed` was never called | Call `core.setFailed` in the `catch` block |
| Output is empty in later step | Step has no `id`, or the output name differs | Add `id:` and match the output name |
Summary of the model
A JavaScript action is a folder with action.yml and a script. The runner converts inputs to INPUT_* environment variables, starts Node on the main file, and reads outputs and the exit code when the process ends. Your script must reach its dependencies without an install step, must treat all inputs as strings, and must report failures through core.setFailed so the step status is accurate.
Exercise
A workflow passes with: dry-run: false to your action. The script contains if (core.getInput('dry-run')) { console.log('Dry run'); }, and it prints "Dry run" every time. Why does this happen, and how do you fix it?
Show answer
Inputs arrive as strings, and core.getInput returns the string "false", which is non-empty and therefore truthy in JavaScript. Use core.getBooleanInput('dry-run'), which converts "true" and "false" to real booleans and throws on other values.
Exercise
Your action works when you run node index.js on your laptop, but the step fails on the runner with Cannot find module '@actions/core'. What is missing, and what are two ways to resolve it?
Show answer
The runner does not run npm install for an action, so the packages in node_modules are absent from the checked-out action. You can commit node_modules/ to the repository, or bundle the script and its dependencies into a single file (for example with @vercel/ncc), point main at that file, and commit it.
Exercise
In a script that calls core.setFailed('bad input') inside a validation function, extra work still runs afterward and a later API call is made. Why, and what change prevents it?
Show answer
core.setFailed only logs the error and sets the exit code to 1. It does not stop execution. Return from the function (or the run function) right after calling it, so the remaining code does not execute.