npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@octokit/webhooks

v13.4.1

Published

GitHub webhook events toolset for Node.js

Downloads

4,607,197

Readme

@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.

| Event | Actions | | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | branch_protection_configuration | disabledenabled | | branch_protection_rule | createddeletededited | | check_run | completedcreatedrequested_actionrerequested | | check_suite | completedrequestedrerequested | | code_scanning_alert | appeared_in_branchclosed_by_usercreatedfixedreopenedreopened_by_user | | commit_comment | created | | create | | | custom_property | createddeletedupdated | | custom_property_values | updated | | delete | | | dependabot_alert | auto_dismissedauto_reopenedcreateddismissedfixedreintroducedreopened | | deploy_key | createddeleted | | deployment | created | | deployment_protection_rule | requested | | deployment_review | approvedrejectedrequested | | deployment_status | created | | discussion | answeredcategory_changedclosedcreateddeletededitedlabeledlockedpinnedreopenedtransferredunansweredunlabeledunlockedunpinned | | discussion_comment | createddeletededited | | fork | | | github_app_authorization | revoked | | gollum | | | installation | createddeletednew_permissions_acceptedsuspendunsuspend | | installation_repositories | addedremoved | | installation_target | renamed | | issue_comment | createddeletededited | | issues | assignedcloseddeleteddemilestonededitedlabeledlockedmilestonedopenedpinnedreopenedtransferredunassignedunlabeledunlockedunpinned | | label | createddeletededited | | marketplace_purchase | cancelledchangedpending_changepending_change_cancelledpurchased | | member | addededitedremoved | | membership | addedremoved | | merge_group | checks_requesteddestroyed | | meta | deleted | | milestone | closedcreateddeletededitedopened | | org_block | blockedunblocked | | organization | deletedmember_addedmember_invitedmember_removedrenamed | | package | publishedupdated | | page_build | | | personal_access_token_request | approvedcancelledcreateddenied | | ping | | | project | closedcreateddeletededitedreopened | | project_card | convertedcreateddeletededitedmoved | | project_column | createddeletededitedmoved | | projects_v2 | closedcreateddeletededitedreopened | | projects_v2_item | archivedconvertedcreateddeletededitedreorderedrestored | | projects_v2_status_update | createddeletededited | | public | | | pull_request | assignedauto_merge_disabledauto_merge_enabledclosedconverted_to_draftdemilestoneddequeuededitedenqueuedlabeledlockedmilestonedopenedready_for_reviewreopenedreview_request_removedreview_requestedsynchronizeunassignedunlabeledunlocked | | pull_request_review | dismissededitedsubmitted | | pull_request_review_comment | createddeletededited | | pull_request_review_thread | resolvedunresolved | | push | | | registry_package | publishedupdated | | release | createddeletededitedprereleasedpublishedreleasedunpublished | | repository | archivedcreateddeletededitedprivatizedpublicizedrenamedtransferredunarchived | | repository_advisory | publishedreported | | repository_dispatch | sample | | repository_import | | | repository_ruleset | createddeletededited | | repository_vulnerability_alert | createdismissreopenresolve | | secret_scanning_alert | createdreopenedresolvedvalidated | | secret_scanning_alert_location | created | | security_advisory | publishedupdatedwithdrawn | | security_and_analysis | | | sponsorship | cancelledcreatededitedpending_cancellationpending_tier_changetier_changed | | star | createddeleted | | status | | | sub_issues | parent_issue_addedparent_issue_removedsub_issue_addedsub_issue_removed | | team | added_to_repositorycreateddeletededitedremoved_from_repository | | team_add | | | watch | started | | workflow_dispatch | | | workflow_job | completedin_progressqueuedwaiting | | workflow_run | completedin_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