13.2.6 • Published 3 days ago

@octokit/webhooks v13.2.6

Weekly downloads
51,554
License
MIT
Repository
github
Last release
3 days ago

@octokit/webhooks

GitHub webhook events toolset for Node.js

@latest Test

@octokit/webhooks helps to handle webhook events received from GitHub.

GitHub webhooks can be registered in multiple ways

  1. In repository or organization settings on github.com.
  2. Using the REST API for repositories or organizations
  3. By creating a GitHub App.

Note that while setting a secret is optional on GitHub, it is required to be set in order to use @octokit/webhooks. Content Type must be set to application/json, application/x-www-form-urlencoded is not supported.

Usage

// install with: npm install @octokit/webhooks
import { Webhooks, createNodeMiddleware } from "@octokit/webhooks";
import { createServer } from "node:http";
const webhooks = new Webhooks({
  secret: "mysecret",
});

webhooks.onAny(({ id, name, payload }) => {
  console.log(name, "event received");
});

createServer(createNodeMiddleware(webhooks)).listen(3000);
// can now receive webhook events at /api/github/webhooks

Local development

You can receive webhooks on your local machine or even browser using EventSource and smee.io.

Go to smee.io and Start a new channel. Then copy the "Webhook Proxy URL" and

  1. enter it in the GitHub App’s "Webhook URL" input
  2. pass it to the EventSource constructor, see below
const webhookProxyUrl = "https://smee.io/IrqK0nopGAOc847"; // replace with your own Webhook Proxy URL
const source = new EventSource(webhookProxyUrl);
source.onmessage = (event) => {
  const webhookEvent = JSON.parse(event.data);
  webhooks
    .verifyAndReceive({
      id: webhookEvent["x-request-id"],
      name: webhookEvent["x-github-event"],
      signature: webhookEvent["x-hub-signature"],
      payload: JSON.stringify(webhookEvent.body),
    })
    .catch(console.error);
};

EventSource is a native browser API and can be polyfilled for browsers that don’t support it. In node, you can use the eventsource package: install with npm install eventsource, then import EventSource from "eventsource";)

API

  1. Constructor
  2. webhooks.sign()
  3. webhooks.verify()
  4. webhooks.verifyAndReceive()
  5. webhooks.receive()
  6. webhooks.on()
  7. webhooks.onAny()
  8. webhooks.onError()
  9. webhooks.removeListener()
  10. createNodeMiddleware()
  11. Webhook events
  12. emitterEventNames

Constructor

new Webhooks({ secret /*, transform */ });

Used for internal logging. Defaults to console with debug and info doing nothing.

Returns the webhooks API.

webhooks.sign()

webhooks.sign(eventPayload);

Returns a signature string. Throws error if eventPayload is not passed.

The sign method can be imported as static method from @octokit/webhooks-methods.

webhooks.verify()

webhooks.verify(eventPayload, signature);

Returns true or false. Throws error if eventPayload or signature not passed.

The verify method can be imported as static method from @octokit/webhooks-methods.

webhooks.verifyAndReceive()

webhooks.verifyAndReceive({ id, name, payload, signature });

Returns a promise.

Verifies event using webhooks.verify(), then handles the event using webhooks.receive().

Additionally, if verification fails, rejects the returned promise and emits an error event.

Example

import { Webhooks } from "@octokit/webhooks";
const webhooks = new Webhooks({
  secret: "mysecret",
});
eventHandler.on("error", handleSignatureVerificationError);

// put this inside your webhooks route handler
eventHandler
  .verifyAndReceive({
    id: request.headers["x-github-delivery"],
    name: request.headers["x-github-event"],
    payload: request.body,
    signature: request.headers["x-hub-signature-256"],
  })
  .catch(handleErrorsFromHooks);

webhooks.receive()

webhooks.receive({ id, name, payload });

Returns a promise. Runs all handlers set with webhooks.on() in parallel and waits for them to finish. If one of the handlers rejects or throws an error, then webhooks.receive() rejects. The returned error has an .errors property which holds an array of all errors caught from the handlers. If no errors occur, webhooks.receive() resolves without passing any value.

The .receive() method belongs to the event-handler module which can be used standalone.

webhooks.on()

webhooks.on(eventName, handler);
webhooks.on(eventNames, handler);

The .on() method belongs to the event-handler module which can be used standalone.

webhooks.onAny()

webhooks.onAny(handler);

The .onAny() method belongs to the event-handler module which can be used standalone.

webhooks.onError()

webhooks.onError(handler);

If a webhook event handler throws an error or returns a promise that rejects, an error event is triggered. You can use this handler for logging or reporting events. The passed error object has a .event property which has all information on the event.

Asynchronous error event handler are not blocking the .receive() method from completing.

The .onError() method belongs to the event-handler module which can be used standalone.

webhooks.removeListener()

webhooks.removeListener(eventName, handler);
webhooks.removeListener(eventNames, handler);

The .removeListener() method belongs to the event-handler module which can be used standalone.

createNodeMiddleware()

import { createServer } from "node:http";
import { Webhooks, createNodeMiddleware } from "@octokit/webhooks";

const webhooks = new Webhooks({
  secret: "mysecret",
});

const middleware = createNodeMiddleware(webhooks, { path: "/webhooks" });
createServer(async (req, res) => {
  // `middleware` returns `false` when `req` is unhandled (beyond `/webhooks`)
  if (await middleware(req, res)) return;
  res.writeHead(404);
  res.end();
}).listen(3000);
// can now receive user authorization callbacks at POST /webhooks

The middleware returned from createNodeMiddleware can also serve as an Express.js middleware directly.

Used for internal logging. Defaults to console with debug and info doing nothing.

Webhook events

See the full list of event types with example payloads.

If there are actions for a webhook, events are emitted for both, the webhook name as well as a combination of the webhook name and the action, e.g. installation and installation.created.

EventActions
branch_protection_configurationdisabledenabled
branch_protection_rulecreateddeletededited
check_runcompletedcreatedrequested_actionrerequested
check_suitecompletedrequestedrerequested
code_scanning_alertappeared_in_branchclosed_by_usercreatedfixedreopenedreopened_by_user
commit_commentcreated
create
custom_propertycreateddeletedupdated
custom_property_valuesupdated
delete
dependabot_alertauto_dismissedauto_reopenedcreateddismissedfixedreintroducedreopened
deploy_keycreateddeleted
deploymentcreated
deployment_protection_rulerequested
deployment_reviewapprovedrejectedrequested
deployment_statuscreated
discussionansweredcategory_changedclosedcreateddeletededitedlabeledlockedpinnedreopenedtransferredunansweredunlabeledunlockedunpinned
discussion_commentcreateddeletededited
fork
github_app_authorizationrevoked
gollum
installationcreateddeletednew_permissions_acceptedsuspendunsuspend
installation_repositoriesaddedremoved
installation_targetrenamed
issue_commentcreateddeletededited
issuesassignedcloseddeleteddemilestonededitedlabeledlockedmilestonedopenedpinnedreopenedtransferredunassignedunlabeledunlockedunpinned
labelcreateddeletededited
marketplace_purchasecancelledchangedpending_changepending_change_cancelledpurchased
memberaddededitedremoved
membershipaddedremoved
merge_groupchecks_requesteddestroyed
metadeleted
milestoneclosedcreateddeletededitedopened
org_blockblockedunblocked
organizationdeletedmember_addedmember_invitedmember_removedrenamed
packagepublishedupdated
page_build
personal_access_token_requestapprovedcancelledcreateddenied
ping
projectclosedcreateddeletededitedreopened
project_cardconvertedcreateddeletededitedmoved
project_columncreateddeletededitedmoved
projects_v2closedcreateddeletededitedreopened
projects_v2_itemarchivedconvertedcreateddeletededitedreorderedrestored
public
pull_requestassignedauto_merge_disabledauto_merge_enabledclosedconverted_to_draftdemilestoneddequeuededitedenqueuedlabeledlockedmilestonedopenedready_for_reviewreopenedreview_request_removedreview_requestedsynchronizeunassignedunlabeledunlocked
pull_request_reviewdismissededitedsubmitted
pull_request_review_commentcreateddeletededited
pull_request_review_threadresolvedunresolved
push
registry_packagepublishedupdated
releasecreateddeletededitedprereleasedpublishedreleasedunpublished
repositoryarchivedcreateddeletededitedprivatizedpublicizedrenamedtransferredunarchived
repository_advisorypublishedreported
repository_dispatchsample
repository_import
repository_rulesetcreateddeletededited
repository_vulnerability_alertcreatedismissreopenresolve
secret_scanning_alertcreatedreopenedresolvedrevokedvalidated
secret_scanning_alert_locationcreated
security_advisorypublishedupdatedwithdrawn
security_and_analysis
sponsorshipcancelledcreatededitedpending_cancellationpending_tier_changetier_changed
starcreateddeleted
status
teamadded_to_repositorycreateddeletededitedremoved_from_repository
team_add
watchstarted
workflow_dispatch
workflow_jobcompletedin_progressqueuedwaiting
workflow_runcompletedin_progressrequested

emitterEventNames

A read only tuple containing all the possible combinations of the webhook events + actions listed above. This might be useful in GUI and input validation.

import { emitterEventNames } from "@octokit/webhooks";
emitterEventNames; // ["check_run", "check_run.completed", ...]

TypeScript

The types for the webhook payloads are sourced from @octokit/openapi-webhooks-types, which can be used by themselves.

In addition to these types, @octokit/webhooks exports 2 types specific to itself:

Note that changes to the exported types are not considered breaking changes, as the changes will not impact production code, but only fail locally or during CI at build time.

!IMPORTANT As we use conditional exports, you will need to adapt your tsconfig.json by setting "moduleResolution": "node16", "module": "node16".

See the TypeScript docs on package.json "exports". See this helpful guide on transitioning to ESM from @sindresorhus

⚠️ Caution ⚠️: Webhooks Types are expected to be used with the strictNullChecks option enabled in your tsconfig. If you don't have this option enabled, there's the possibility that you get never as the inferred type in some use cases. See octokit/webhooks#395 for details.

EmitterWebhookEventName

A union of all possible events and event/action combinations supported by the event emitter, e.g. "check_run" | "check_run.completed" | ... many more ... | "workflow_run.requested".

EmitterWebhookEvent

The object that is emitted by @octokit/webhooks as an event; made up of an id, name, and payload properties. An optional generic parameter can be passed to narrow the type of the name and payload properties based on event names or event/action combinations, e.g. EmitterWebhookEvent<"check_run" | "code_scanning_alert.fixed">.

License

MIT

@balena/versionbot@githaxs/action-app-wrapper@githaxs/github-application-wrapper@knapsack/api-server@everything-registry/sub-chunk-676@quantum-sec/xdr-updaterpullup-sandboxrelease-please-botreshuffle-github-connectorprobot-kitprobot-tsprobotredhatinsights-plugin-scaffolder-backendtickettaggerel-botekam-servicegithookerlabel-approved-actionkoishi-plugin-github-webhookgithub-webhook-validatorsgithub-webhooks-execozyiftttcubohubworkflow-dispatch-syncdelete-merged-actiondmt-backend@jbrunton/gha-installer@infinitebrahmanuniverse/nolb-_oc@probot-ng/core@pikokr/pm2-auto-update@ploys/deployments-core@ptabor/github-actions@r3m0t/vscode-jupyter@nestjs-shared/probot@mgrbot/webhook-github@monstrs/nestjs-github-app@nylas/create-linked-clubhouse-story@octokit/app@ericlai616/reviewer-assignment-bot@trigger.dev/github@ubiquibot/permit-generation@wordpress/project-management-automation@yieldbits/probot@vrabbi/plugin-scaffolder-backend@skynet1024/probot@telus/colophon-app@zhinjs/plugin-github@stepsize/shared-types@stepsize/tywinagba-merger@webqit/webfloautomoto@audibene/plugin-scaffolder-backend@backstage/plugin-scaffolder-backend-module-github@barajs/githubbuildci-plugin-githubbackport-github-action@binarymuse/probot@colophon/appcarlin@curiostack/cloudbuild-github@dendra-science/github-webhook-nats-streaming@ddcp/github-mirror@denizhoxha/probot@deliverybot/app@deliverybot/core@dependencies/appcheck-pull-requestcloudbuild-task-github-actionscloudfunc-gh-hook@dopry/pecanscreate-linked-clubhouse-story
13.2.6

3 days ago

13.2.5

6 days ago

13.2.4

9 days ago

13.2.3

15 days ago

13.2.2

23 days ago

13.2.0

25 days ago

13.2.1

25 days ago

12.2.0

1 month ago

13.1.1

2 months ago

13.1.0

2 months ago

13.0.2

2 months ago

13.0.0-beta.6

2 months ago

13.0.0-beta.5

2 months ago

13.0.0

2 months ago

13.0.1

2 months ago

13.0.0-beta.4

2 months ago

13.0.0-beta.3

2 months ago

12.1.2

2 months ago

13.0.0-beta.2

2 months ago

12.1.1

2 months ago

13.0.0-beta.1

3 months ago

12.2.0-beta.1

3 months ago

12.1.0

3 months ago

12.0.11

4 months ago

12.0.9

5 months ago

12.0.10

5 months ago

10.9.2

6 months ago

12.0.7

5 months ago

12.0.8

5 months ago

12.0.3

10 months ago

12.0.4

6 months ago

12.0.5

5 months ago

12.0.6

5 months ago

12.0.2

10 months ago

11.1.2

6 months ago

9.26.1

6 months ago

9.26.2

6 months ago

9.26.3

6 months ago

12.0.0

11 months ago

12.0.1

11 months ago

11.1.1

11 months ago

11.1.0

11 months ago

10.8.0

1 year ago

11.0.0-beta.10

1 year ago

10.7.1

1 year ago

10.7.2

1 year ago

10.7.3

1 year ago

11.0.0

1 year ago

10.9.0

1 year ago

10.9.1

1 year ago

11.0.0-beta.8

1 year ago

11.0.0-beta.9

1 year ago

10.7.0

1 year ago

10.4.0

1 year ago

11.0.0-beta.3

1 year ago

11.0.0-beta.4

1 year ago

10.6.0

1 year ago

10.6.1

1 year ago

10.6.2

1 year ago

11.0.0-beta.5

1 year ago

11.0.0-beta.6

1 year ago

11.0.0-beta.7

1 year ago

10.5.0

1 year ago

10.5.1

1 year ago

10.3.0

2 years ago

10.3.1

2 years ago

11.0.0-beta.2

2 years ago

10.2.0

2 years ago

11.0.0-beta.1

2 years ago

10.0.5

2 years ago

10.0.6

2 years ago

10.0.7

2 years ago

10.0.8

2 years ago

10.0.9

2 years ago

10.0.0

2 years ago

10.0.1

2 years ago

10.0.2

2 years ago

10.0.3

2 years ago

10.0.4

2 years ago

9.26.0

2 years ago

10.1.4

2 years ago

10.1.5

2 years ago

10.1.0

2 years ago

10.1.1

2 years ago

10.1.2

2 years ago

10.1.3

2 years ago

9.25.0

2 years ago

9.24.0

2 years ago

9.23.0

2 years ago

9.22.0

2 years ago

9.20.0

2 years ago

9.19.0

2 years ago

9.18.0

2 years ago

9.21.0

2 years ago

9.16.0

3 years ago

9.17.0

3 years ago

9.15.1

3 years ago

9.15.0

3 years ago

9.14.2

3 years ago

9.14.1

3 years ago

9.14.0

3 years ago

9.13.0

3 years ago

9.12.0

3 years ago

9.11.0

3 years ago

9.10.0

3 years ago

9.9.0

3 years ago

9.8.4

3 years ago

9.8.3

3 years ago

9.8.2

3 years ago

9.8.1

3 years ago

9.8.0

3 years ago

9.6.3

3 years ago

9.7.0

3 years ago

9.4.0

3 years ago

9.5.1

3 years ago

9.5.0

3 years ago

9.1.2

3 years ago

9.6.2

3 years ago

9.6.1

3 years ago

9.6.0

3 years ago

9.1.1

3 years ago

9.1.0

3 years ago

9.3.0

3 years ago

9.2.0

3 years ago

9.0.1

3 years ago

9.0.0

3 years ago

8.12.3

3 years ago

8.12.2

3 years ago

9.0.0-beta.5

3 years ago

8.12.1

3 years ago

9.0.0-beta.4

3 years ago

8.12.0

3 years ago

8.11.1

3 years ago

8.11.0

3 years ago

8.11.2

3 years ago

9.0.0-beta.3

3 years ago

9.0.0-beta.2

3 years ago

9.0.0-beta.1

3 years ago

8.10.0

3 years ago

8.10.1

3 years ago

8.9.0

3 years ago

8.8.1

3 years ago

8.8.3

3 years ago

8.8.2

3 years ago

8.8.0

3 years ago

8.6.2

3 years ago

8.6.1

3 years ago

8.7.2

3 years ago

8.7.1

3 years ago

8.7.0

3 years ago

8.6.0

3 years ago

8.5.4

3 years ago

8.5.3

3 years ago

8.5.2

3 years ago

8.5.1

3 years ago

8.5.0

3 years ago

8.4.1

3 years ago

8.4.0

3 years ago

8.3.0

3 years ago

8.1.0

3 years ago

8.1.1

3 years ago

8.2.0

3 years ago

8.0.3

3 years ago

8.0.2

3 years ago

7.24.3

3 years ago

8.0.1

3 years ago

8.0.0

3 years ago

7.24.2

3 years ago

7.24.1

3 years ago

7.23.0

3 years ago

7.22.0

3 years ago

7.21.0

3 years ago

7.20.1

3 years ago

7.20.0

3 years ago

7.19.0

3 years ago

7.18.3

3 years ago

7.18.2

3 years ago

7.18.1

3 years ago

7.18.0

3 years ago

7.17.0

3 years ago

7.16.1

3 years ago

7.16.0

3 years ago

7.15.2

3 years ago

7.15.1

4 years ago

7.15.0

4 years ago

7.14.0

4 years ago

7.13.1

4 years ago

7.13.0

4 years ago

7.12.2

4 years ago

7.12.1

4 years ago

7.12.0

4 years ago

7.11.4

4 years ago

7.11.3

4 years ago

7.11.2

4 years ago

7.11.1

4 years ago

7.11.0

4 years ago

7.10.0

4 years ago

7.9.4

4 years ago

7.9.3

4 years ago

7.9.2

4 years ago

7.9.1

4 years ago

7.9.0

4 years ago

7.8.2

4 years ago

7.8.1

4 years ago

7.8.0

4 years ago

7.7.0

4 years ago

7.6.5

4 years ago

7.6.4

4 years ago

7.6.3

4 years ago

7.6.2

4 years ago

7.6.1

4 years ago

7.6.0

4 years ago

7.5.0

4 years ago

7.4.0

4 years ago

7.3.0

4 years ago

7.2.0

4 years ago

7.1.2

4 years ago

7.1.1

4 years ago

7.1.0

4 years ago

7.0.0

4 years ago

6.3.2

5 years ago

6.3.1

5 years ago

6.3.0

5 years ago

6.2.2

5 years ago

6.2.1

5 years ago

6.2.0

5 years ago

6.1.0

5 years ago

6.0.1

5 years ago

6.0.0

5 years ago

5.4.1

5 years ago

5.4.0

5 years ago

5.3.4

5 years ago

5.3.3

5 years ago

5.3.2

5 years ago

5.3.1

5 years ago

5.3.0

5 years ago

5.2.0

5 years ago

5.1.2

5 years ago

5.1.1

5 years ago

5.1.0

5 years ago

5.0.3

5 years ago

5.0.2

6 years ago

5.0.1

6 years ago

5.0.0

6 years ago

4.0.0

6 years ago

3.1.1

6 years ago

3.1.0

6 years ago

3.0.2

6 years ago

3.0.1

6 years ago

3.0.0

6 years ago

2.0.0

6 years ago

1.0.0

6 years ago