Sub topic 5
Using @actions/core and @actions/github
This chapter covers the two toolkit packages that most JavaScript actions depend on. It assumes you can write a basic action.yml, know how inputs and outputs are declared, and are comfortable with Node and npm. Bundling the code for distribution comes in a later chapter.
Why a toolkit exists
A JavaScript action is a Node program that the runner starts. The runner talks to your program through environment variables and special files. Reading an input means reading an environment variable named INPUT_<NAME>. Setting an output means appending a line to the file named by GITHUB_OUTPUT. You could do this by hand, but the details are easy to get wrong.
The @actions/core package wraps those mechanics. The @actions/github package gives you the event payload and an authenticated API client. Install both:
npm install @actions/core @actions/github| Package | What it gives you | Typical use |
|---|---|---|
| `@actions/core` | Inputs, outputs, logging, failure, secrets masking, state | Every action |
| `@actions/github` | `context` object and `getOctokit` client | Actions that read the event or call the GitHub API |
Reading inputs with core
core.getInput(name) returns the value of an input as a string. Three details matter.
- The lookup is case-insensitive, and spaces in the name become underscores. The runner stores
who-to-greetasINPUT_WHO-TO-GREET, andgetInputhandles that for you. - A missing input returns an empty string, not
undefined. If theaction.ymldeclares adefault, the runner supplies it. - Whitespace around the value is trimmed unless you pass
{ trimWhitespace: false }.
To make the toolkit enforce a required input, pass required: true. It throws if the value is empty.
const core = require('@actions/core');
const name = core.getInput('who-to-greet', { required: true });Every input is a string, so you convert types yourself. The toolkit has helpers for the common cases.
| Function | Returns | Notes |
|---|---|---|
| `getInput(name, options)` | string | Empty string if missing |
| `getBooleanInput(name)` | boolean | Accepts `true`, `True`, `TRUE`, `false`, `False`, `FALSE`. Throws on anything else |
| `getMultilineInput(name)` | string[] | Splits on newlines and drops empty lines |
Do not write if (core.getInput('dry-run')). The string "false" is truthy in JavaScript, so the check passes when the user asked for the opposite. Use getBooleanInput instead.
const dryRun = core.getBooleanInput('dry-run');
const labels = core.getMultilineInput('labels');A caller passes a multiline value with a YAML block scalar:
- uses: ./
with:
dry-run: 'true'
labels: |
bug
needs-triageSetting outputs and logging
core.setOutput(name, value) writes the output so later steps can read it as steps.<id>.outputs.<name>. Under the hood it appends to the GITHUB_OUTPUT file, using a delimiter syntax when the value contains newlines. Values are stored as strings, so objects should go through JSON.stringify.
The logging helpers write workflow commands that the runner understands.
| Function | Effect in the log |
|---|---|
| `core.info(msg)` | Plain line |
| `core.debug(msg)` | Shown only when step debug logging is enabled |
| `core.notice(msg)`, `core.warning(msg)`, `core.error(msg)` | Annotation on the run summary |
| `core.startGroup(name)` / `core.endGroup()` | Collapsible section |
Annotations accept optional properties such as title, file, startLine, and endLine. When you give a file and line, GitHub attaches the annotation to that line in a pull request.
core.warning('Deprecated option used', {
title: 'Config warning',
file: 'config.yml',
startLine: 3,
});Masking secrets
If your action computes or fetches a sensitive value, call core.setSecret(value) before it can reach the log. The runner then replaces any later occurrence of that value with asterisks. Masking is by exact string match, so a transformed copy (for example base64 of the secret) is not masked unless you register it too.
Reading the event with github.context
@actions/github exports context, an object built from environment variables and the event payload file. It is available synchronously, with no API call.
| Property | Meaning |
|---|---|
| `context.eventName` | Event that triggered the run, such as `push` or `pull_request` |
| `context.payload` | The full webhook payload for that event |
| `context.repo` | Object `{ owner, repo }` for the current repository |
| `context.sha`, `context.ref` | Commit SHA and ref that triggered the run |
| `context.workflow`, `context.runId`, `context.actor` | Run metadata |
| `context.issue` | `{ owner, repo, number }` for issue and pull request events |
The shape of payload depends on the event. A pull_request payload has payload.pull_request, while a push payload does not. Code that assumes a field exists will fail on other triggers, so guard for it.
const github = require('@actions/github');
const pr = github.context.payload.pull_request;
if (!pr) {
core.info(`Nothing to do for event ${github.context.eventName}`);
return;
}A top-level return works in CommonJS modules, but it is clearer to put your logic in an async function run() and return from there, as shown in the full example below.
Calling the API with getOctokit
github.getOctokit(token) returns an Octokit client authenticated with the token you give it. The usual pattern is to take the token as an input and let the caller pass ${{ github.token }}.
inputs:
github-token:
description: 'Token used to call the GitHub API'
required: true
default: ${{ github.token }}The client exposes REST methods under octokit.rest. It also exposes octokit.paginate for endpoints that return many pages, and octokit.graphql for GraphQL queries.
const octokit = github.getOctokit(token);
const { data: comment } = await octokit.rest.issues.createComment({
...github.context.repo,
issue_number: pr.number,
body: 'Thanks for the pull request!',
});
core.info(`Created comment ${comment.id}`);The token's permissions decide what succeeds. A workflow's default GITHUB_TOKEN may be read-only, in which case the call above fails with a 403 error. The workflow author fixes this with a permissions: block such as pull-requests: write. Document the permissions your action needs in its README.
A pull request from a fork gets a read-only token regardless of the permissions: block. Plan for that case rather than letting the step crash.
A complete example
The following action comments on a pull request and outputs the comment ID. It ties together inputs, context, the client, and failure handling.
const core = require('@actions/core');
const github = require('@actions/github');
async function run() {
try {
const token = core.getInput('github-token', { required: true });
const message = core.getInput('message', { required: true });
const dryRun = core.getBooleanInput('dry-run');
const pr = github.context.payload.pull_request;
if (!pr) {
core.warning(`Event ${github.context.eventName} has no pull request`);
return;
}
if (dryRun) {
core.info(`Dry run. Would comment: ${message}`);
return;
}
const octokit = github.getOctokit(token);
const { data } = await octokit.rest.issues.createComment({
...github.context.repo,
issue_number: pr.number,
body: message,
});
core.setOutput('comment-id', String(data.id));
} catch (error) {
core.setFailed(error instanceof Error ? error.message : String(error));
}
}
run();The matching metadata declares the three inputs and one output:
name: 'PR Commenter'
description: 'Post a comment on a pull request'
inputs:
github-token:
description: 'Token used to call the GitHub API'
default: ${{ github.token }}
message:
description: 'Comment text'
required: true
dry-run:
description: 'Log instead of posting'
default: 'false'
outputs:
comment-id:
description: 'ID of the created comment'
runs:
using: 'node20'
main: 'index.js'Failure, state, and common errors
core.setFailed(message) logs an error annotation and sets the process exit code to 1, which marks the step as failed. It does not stop your code. Statements after the call still run, so return afterwards if you need to stop. An uncaught exception also fails the step, but with a less useful message, which is why the example wraps everything in try/catch.
The toolkit also provides core.saveState(name, value) and core.getState(name) to pass data from a pre or post script to the main script. Those lifecycle scripts get their own chapter.
Common mistakes:
- Treating
getInputoutput as a boolean. UsegetBooleanInput. - Assuming
payload.pull_requestexists. It exists only on pull request events. - Forgetting
await. An unawaited Octokit call can finish after the process decides the step succeeded, or reject with nothing to catch it. - Using an
asyncfunction without a catch. Rejections inrun()escape unless you catch them. - Passing a number or object to
setOutputand expecting it to stay typed. The consumer always reads a string. - Missing token permissions. A 403 or "Resource not accessible by integration" error points to the
permissions:block.
How the pieces connect
Exercise
A caller sets dry-run: 'false', yet your action still skips the real work because you wrote if (core.getInput('dry-run')) { ... }. Why does this happen, and what is the fix?
Show answer
getInput returns the string "false", and any non-empty string is truthy in JavaScript, so the condition is true. Use core.getBooleanInput('dry-run'), which returns the boolean false for 'false' and throws on values that are not valid booleans.
Exercise
Your action runs on both push and pull_request triggers and reads github.context.payload.pull_request.number. It fails on push with a TypeError. How do you fix it?
Show answer
The push payload has no pull_request field, so the property access fails on undefined. Read const pr = github.context.payload.pull_request, check if (!pr), and then log a message and return (or take a push-specific path) before using pr.number.
Exercise
After core.setFailed('bad config') you have a line that deletes files. Does the deletion run? What do you add?
Show answer
Yes, it runs. setFailed only logs the error and sets the exit code to 1. It does not stop execution. Add a return right after the call, or throw inside the try block so control jumps to the catch.