{"meta":{"title":"Creating a JavaScript action","intro":"In this tutorial, you'll learn how to build a JavaScript action using the actions toolkit.","product":"GitHub Actions","breadcrumbs":[{"href":"/en/enterprise-cloud@latest/actions","title":"GitHub Actions"},{"href":"/en/enterprise-cloud@latest/actions/tutorials","title":"Tutorials"},{"href":"/en/enterprise-cloud@latest/actions/tutorials/create-actions","title":"Create actions"},{"href":"/en/enterprise-cloud@latest/actions/tutorials/create-actions/create-a-javascript-action","title":"Create a JavaScript action"}],"documentType":"article"},"body":"# Creating a JavaScript action\n\nIn this tutorial, you'll learn how to build a JavaScript action using the actions toolkit.\n\n## Introduction\n\nIn this guide, you'll learn about the basic components needed to create and use a packaged JavaScript action. To focus this guide on the components needed to package the action, the functionality of the action's code is minimal. The action prints \"Hello World\" in the logs or \"Hello \\[who-to-greet]\" if you provide a custom name.\n\nThis guide uses the GitHub Actions Toolkit Node.js module to speed up development. For more information, see the [actions/toolkit](https://github.com/actions/toolkit) repository.\n\nOnce you complete this project, you should understand how to build your own JavaScript action and test it in a workflow.\n\nTo ensure your JavaScript actions are compatible with all GitHub-hosted runners (Ubuntu, Windows, and macOS), the packaged JavaScript code you write should be pure JavaScript and not rely on other binaries. JavaScript actions run directly on the runner and use binaries that already exist in the runner image.\n\n> \\[!WARNING]\n> When creating workflows and actions, you should always consider whether your code might execute untrusted input from possible attackers. Certain contexts should be treated as untrusted input, as an attacker could insert their own malicious content. For more information, see [Secure use reference](/en/enterprise-cloud@latest/actions/security-guides/security-hardening-for-github-actions#understanding-the-risk-of-script-injections).\n\n## Prerequisites\n\nBefore you begin, you'll need to download Node.js and create a public GitHub repository.\n\n1. Download and install Node.js 20.x, which includes npm.\n\n   <https://nodejs.org/en/download/>\n\n2. Create a new public repository on GitHub and call it \"hello-world-javascript-action\". For more information, see [Creating a new repository](/en/enterprise-cloud@latest/repositories/creating-and-managing-repositories/creating-a-new-repository).\n\n3. Clone your repository to your computer. For more information, see [Cloning a repository](/en/enterprise-cloud@latest/repositories/creating-and-managing-repositories/cloning-a-repository).\n\n4. From your terminal, change directories into your new repository.\n\n   ```shell copy\n   cd hello-world-javascript-action\n   ```\n\n5. From your terminal, initialize the directory with npm to generate a `package.json` file.\n\n   ```shell copy\n   npm init -y\n   ```\n\n## Creating an action metadata file\n\nCreate a new file named `action.yml` in the `hello-world-javascript-action` directory with the following example code. For more information, see [Metadata syntax reference](/en/enterprise-cloud@latest/actions/creating-actions/metadata-syntax-for-github-actions).\n\n```yaml copy\nname: Hello World\ndescription: Greet someone and record the time\n\ninputs:\n  who-to-greet: # id of input\n    description: Who to greet\n    required: true\n    default: World\n\noutputs:\n  time: # id of output\n    description: The time we greeted you\n\nruns:\n  using: node20\n  main: dist/index.js\n```\n\nThis file defines the `who-to-greet` input and `time` output. It also tells the action runner how to start running this JavaScript action.\n\n## Adding actions toolkit packages\n\nThe actions toolkit is a collection of Node.js packages that allow you to quickly build JavaScript actions with more consistency.\n\nThe toolkit [`@actions/core`](https://github.com/actions/toolkit/tree/main/packages/core) package provides an interface to the workflow commands, input and output variables, exit statuses, and debug messages.\n\nThe toolkit also offers a [`@actions/github`](https://github.com/actions/toolkit/tree/main/packages/github) package that returns an authenticated Octokit REST client and access to GitHub Actions contexts.\n\nThe toolkit offers more than the `core` and `github` packages. For more information, see the [actions/toolkit](https://github.com/actions/toolkit) repository.\n\nAt your terminal, install the actions toolkit `core` and `github` packages.\n\n```shell copy\nnpm install @actions/core @actions/github\n```\n\nYou should now see a `node_modules` directory and a `package-lock.json` file which track any installed dependencies and their versions. You should not commit the `node_modules` directory to your repository.\n\n## Writing the action code\n\nThis action uses the toolkit to get the `who-to-greet` input variable required in the action's metadata file and prints \"Hello \\[who-to-greet]\" in a debug message in the log. Next, the script gets the current time and sets it as an output variable that actions running later in a job can use.\n\nGitHub Actions provide context information about the webhook event, Git refs, workflow, action, and the person who triggered the workflow. To access the context information, you can use the `github` package. The action you'll write will print the webhook event payload to the log.\n\nAdd a new file called `src/index.js`, with the following code.\n\n```javascript copy\nimport * as core from \"@actions/core\";\nimport * as github from \"@actions/github\";\n\ntry {\n  // `who-to-greet` input defined in action metadata file\n  const nameToGreet = core.getInput(\"who-to-greet\");\n  core.info(`Hello ${nameToGreet}!`);\n\n  // Get the current time and set it as an output variable\n  const time = new Date().toTimeString();\n  core.setOutput(\"time\", time);\n\n  // Get the JSON webhook payload for the event that triggered the workflow\n  const payload = JSON.stringify(github.context.payload, undefined, 2);\n  core.info(`The event payload: ${payload}`);\n} catch (error) {\n  core.setFailed(error.message);\n}\n```\n\nIf an error is thrown in the above `index.js` example, `core.setFailed(error.message);` uses the actions toolkit [`@actions/core`](https://github.com/actions/toolkit/tree/main/packages/core) package to log a message and set a failing exit code. For more information, see [Setting exit codes for actions](/en/enterprise-cloud@latest/actions/creating-actions/setting-exit-codes-for-actions).\n\n## Creating a README\n\nTo let people know how to use your action, you can create a README file. A README is most helpful when you plan to share your action publicly, but is also a great way to remind you or your team how to use the action.\n\nIn your `hello-world-javascript-action` directory, create a `README.md` file that specifies the following information:\n\n* A detailed description of what the action does.\n* Required input and output arguments.\n* Optional input and output arguments.\n* Secrets the action uses.\n* Environment variables the action uses.\n* An example of how to use your action in a workflow.\n\n````markdown copy\n# Hello world JavaScript action\n\nThis action prints \"Hello World\" or \"Hello\" + the name of a person to greet to the log.\n\n## Inputs\n\n### `who-to-greet`\n\n**Required** The name of the person to greet. Default `\"World\"`.\n\n## Outputs\n\n### `time`\n\nThe time we greeted you.\n\n## Example usage\n\n```yaml\nuses: actions/hello-world-javascript-action@e76147da8e5c81eaf017dede5645551d4b94427b\nwith:\n  who-to-greet: Mona the Octocat\n```\n````\n\n## Commit, tag, and push your action\n\nGitHub downloads each action run in a workflow during runtime and executes it as a complete package of code before you can use workflow commands like `run` to interact with the runner machine. This means you must include any package dependencies required to run the JavaScript code. For example, this action uses `@actions/core` and `@actions/github` packages.\n\nChecking in your `node_modules` directory can cause problems. As an alternative, you can use tools such as [`rollup.js`](https://github.com/rollup/rollup) or [`@vercel/ncc`](https://github.com/vercel/ncc) to combine your code and dependencies into one file for distribution.\n\n1. Install `rollup` and its plugins by running this command in your terminal.\n\n   `npm install --save-dev rollup @rollup/plugin-commonjs @rollup/plugin-node-resolve`\n\n2. Create a new file called `rollup.config.js` in the root of your repository with the following code.\n\n   ```javascript copy\n   import commonjs from \"@rollup/plugin-commonjs\";\n   import { nodeResolve } from \"@rollup/plugin-node-resolve\";\n\n   const config = {\n     input: \"src/index.js\",\n     output: {\n       esModule: true,\n       file: \"dist/index.js\",\n       format: \"es\",\n       sourcemap: true,\n     },\n     plugins: [commonjs(), nodeResolve({ preferBuiltins: true })],\n   };\n\n   export default config;\n   ```\n\n3. Compile your `dist/index.js` file.\n\n   `rollup --config rollup.config.js`\n\n   You'll see a new `dist/index.js` file with your code and any dependencies.\n\n4. From your terminal, commit the updates.\n\n   ```shell copy\n   git add src/index.js dist/index.js rollup.config.js package.json package-lock.json README.md action.yml\n   git commit -m \"Initial commit of my first action\"\n   git tag -a -m \"My first action release\" v1.1\n   git push --follow-tags\n   ```\n\nWhen you commit and push your code, your updated repository should look like this:\n\n```text\nhello-world-javascript-action/\n├── action.yml\n├── dist/\n│   └── index.js\n├── package.json\n├── package-lock.json\n├── README.md\n├── rollup.config.js\n└── src/\n    └── index.js\n```\n\n## Testing out your action in a workflow\n\nNow you're ready to test your action out in a workflow.\n\nPublic actions can be used by workflows in any repository. When an action is in a private or internal repository, the repository settings dictate whether the action is available only within the same repository or also to other repositories owned by the same organization or enterprise. For more information, see [Managing GitHub Actions settings for a repository](/en/enterprise-cloud@latest/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository).\n\n### Example using a public action\n\nThis example demonstrates how your new public action can be run from within an external repository.\n\nCopy the following YAML into a new file at `.github/workflows/main.yml`, and update the `uses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b` line with your username and the name of the public repository you created above. You can also replace the `who-to-greet` input with your name.\n\n```yaml copy\non:\n  push:\n    branches:\n      - main\n\njobs:\n  hello_world_job:\n    name: A job to say hello\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Hello world action step\n        id: hello\n        uses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b\n        with:\n          who-to-greet: Mona the Octocat\n\n      # Use the output from the `hello` step\n      - name: Get the output time\n        run: echo \"The time was ${{ steps.hello.outputs.time }}\"\n```\n\nWhen this workflow is triggered, the runner will download the `hello-world-javascript-action` action from your public repository and then execute it.\n\n### Example using a private action\n\nCopy the workflow code into a `.github/workflows/main.yml` file in your action's repository. You can also replace the `who-to-greet` input with your name.\n\n```yaml copy\non:\n  push:\n    branches:\n      - main\n\njobs:\n  hello_world_job:\n    name: A job to say hello\n    runs-on: ubuntu-latest\n\n    steps:\n      # To use this repository's private action,\n      # you must check out the repository\n      - name: Checkout\n        uses: actions/checkout@v6\n\n      - name: Hello world action step\n        uses: ./ # Uses an action in the root directory\n        id: hello\n        with:\n          who-to-greet: Mona the Octocat\n\n      # Use the output from the `hello` step\n      - name: Get the output time\n        run: echo \"The time was ${{ steps.hello.outputs.time }}\"\n```\n\nFrom your repository, click the **Actions** tab, and select the latest workflow run. Under **Jobs** or in the visualization graph, click **A job to say hello**.\n\nClick **Hello world action step**, and you should see \"Hello Mona the Octocat\" or the name you used for the `who-to-greet` input printed in the log. To see the timestamp, click **Get the output time**.\n\n## Template repositories for creating JavaScript actions\n\nGitHub provides template repositories for creating JavaScript and TypeScript actions. You can use these templates to quickly get started with creating a new action that includes tests, linting, and other recommended practices.\n\n* [`javascript-action` template repository](https://github.com/actions/javascript-action)\n* [`typescript-action` template repository](https://github.com/actions/typescript-action)\n\n## Example JavaScript actions on GitHub.com\n\nYou can find many examples of JavaScript actions on GitHub.com.\n\n* [DevExpress/testcafe-action](https://github.com/DevExpress/testcafe-action)\n* [duckduckgo/privacy-configuration](https://github.com/duckduckgo/privacy-configuration)"}