Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

GitHub webhook events toolset for Node.js

License

NotificationsYou must be signed in to change notification settings

octokit/webhooks.js

Repository files navigation

GitHub webhook events toolset for Node.js

@latestTest

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

GitHub webhooks can be registered in multiple ways

  1. In repository or organization settings ongithub.com.
  2. Using the REST API forrepositories ororganizations
  3. Bycreating 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 toapplication/json,application/x-www-form-urlencoded is not supported.

Usage

// install with: npm install@octokit/webhooksimport{Webhooks,createNodeMiddleware}from"@octokit/webhooks";import{createServer}from"node:http";constwebhooks=newWebhooks({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 usingEventSource andsmee.io.

Go tosmee.io andStart 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 theEventSource constructor, see below
constwebhookProxyUrl="https://smee.io/IrqK0nopGAOc847";// replace with your own Webhook Proxy URLconstsource=newEventSource(webhookProxyUrl);source.onmessage=(event)=>{constwebhookEvent=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 theeventsource package: install withnpm install eventsource, thenimport 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. createWebMiddleware()
  12. Webhook events
  13. emitterEventNames
  14. validateEventName

Constructor

newWebhooks({ secret/*, transform */});
secret(String)Required. Secret as configured in GitHub Settings.
transform(Function) Only relevant forwebhooks.on. Transform emitted event before calling handlers. Can be asynchronous.
log object

Used for internal logging. Defaults toconsole withdebug andinfo doing nothing.

Returns thewebhooks API.

webhooks.sign()

webhooks.sign(eventPayload);
eventPayload (String)Required. Webhook request payload as received from GitHub

Returns asignature string. Throws error ifeventPayload is not passed.

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

webhooks.verify()

webhooks.verify(eventPayload,signature);
eventPayload (String)Required. Webhook event request payload as received from GitHub.
signature (String)Required. Signature string as calculated bywebhooks.sign().

Returnstrue orfalse. Throws error ifeventPayload orsignature not passed.

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

webhooks.verifyAndReceive()

webhooks.verifyAndReceive({ id, name, payload, signature});
id String Unique webhook event request id
name StringRequired. Name of the event. (Event names are set asX-GitHub-Event header in the webhook event request.)
payload StringRequired. Webhook event request payload as received from GitHub.
signature (String)Required. Signature string as calculated bywebhooks.sign().

Returns a promise.

Verifies event usingwebhooks.verify(), then handles the event usingwebhooks.receive().

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

Example

import{Webhooks}from"@octokit/webhooks";constwebhooks=newWebhooks({secret:"mysecret",});eventHandler.on("error",handleSignatureVerificationError);// put this inside your webhooks route handlereventHandler.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});
id String Unique webhook event request id
name StringRequired. Name of the event. (Event names are set asX-GitHub-Event header in the webhook event request.)
payload ObjectRequired. Webhook event request payload as received from GitHub.

Returns a promise. Runs all handlers set withwebhooks.on() in parallel and waits for them to finish. If one of the handlers rejects or throws an error, thenwebhooks.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 theevent-handler module which can be usedstandalone.

webhooks.on()

webhooks.on(eventName,handler);webhooks.on(eventNames,handler);
eventName StringRequired. Name of the event. One ofGitHub's supported event names, or (if the event has an action property) the name of an event followed by its action in the form of<event>.<action>.
eventNames ArrayRequired. Array of event names.
handler FunctionRequired. Method to be run each time the event with the passed name is received. thehandler function can be an async function, throw an error or return a Promise. The handler is called with an event object:{id, name, payload}.

The.on() method belongs to theevent-handler module which can be usedstandalone.

webhooks.onAny()

webhooks.onAny(handler);
handler FunctionRequired. Method to be run each time any event is received. thehandler function can be an async function, throw an error or return a Promise. The handler is called with an event object:{id, name, payload}.

The.onAny() method belongs to theevent-handler module which can be usedstandalone.

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.

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

handler FunctionRequired. Method to be run each time a webhook event handler throws an error or returns a promise that rejects. Thehandler function can be an async function, return a Promise. The handler is called with an error object that has a .event property which has all the information on the event:{id, name, payload}.

The.onError() method belongs to theevent-handler module which can be usedstandalone.

webhooks.removeListener()

webhooks.removeListener(eventName,handler);webhooks.removeListener(eventNames,handler);
eventName StringRequired. Name of the event. One ofGitHub's supported event names, or (if the event has an action property) the name of an event followed by its action in the form of<event>.<action>, or '*' for theonAny() method or 'error' for theonError() method.
eventNames ArrayRequired. Array of event names.
handler FunctionRequired. Method which was previously passed towebhooks.on(). If the same handler was registered multiple times for the same event, only the most recent handler gets removed.

The.removeListener() method belongs to theevent-handler module which can be usedstandalone.

createNodeMiddleware()

import{createServer}from"node:http";import{Webhooks,createNodeMiddleware}from"@octokit/webhooks";constwebhooks=newWebhooks({secret:"mysecret",});constmiddleware=createNodeMiddleware(webhooks,{path:"/webhooks"});createServer(async(req,res)=>{// `middleware` returns `false` when `req` is unhandled (beyond `/webhooks`)if(awaitmiddleware(req,res))return;res.writeHead(404);res.end();}).listen(3000);// can now receive user authorization callbacks at POST /webhooks

The middleware returned fromcreateNodeMiddleware can also serve as anExpress.js middleware directly.

webhooks Webhooks instanceRequired.
path string Custom path to match requests against. Defaults to/api/github/webhooks.
log object

Used for internal logging. Defaults toconsole withdebug andinfo doing nothing.

createWebMiddleware()

import{Webhooks,createWebMiddleware}from"@octokit/webhooks";constwebhooks=newWebhooks({secret:"mysecret",});constmiddleware=createWebMiddleware(webhooks,{path:"/webhooks"});// Example usage in DenoDeno.serve({port:3000},middleware);

The middleware returned fromcreateWebMiddleware can also be used in serverless environments like AWS Lambda, Cloudflare Workers, and Vercel.

webhooks Webhooks instanceRequired.
path string Custom path to match requests against. Defaults to/api/github/webhooks.
log object

Used for internal logging. Defaults toconsole withdebug andinfo doing nothing.

Webhook events

See the full list ofevent 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 andinstallation.created.

EventActions
branch_protection_configurationdisabled
enabled
branch_protection_rulecreated
deleted
edited
check_runcompleted
created
requested_action
rerequested
check_suitecompleted
requested
rerequested
code_scanning_alertappeared_in_branch
closed_by_user
created
fixed
reopened
reopened_by_user
commit_commentcreated
create
custom_propertycreated
deleted
promote_to_enterprise
updated
custom_property_valuesupdated
delete
dependabot_alertauto_dismissed
auto_reopened
created
dismissed
fixed
reintroduced
reopened
deploy_keycreated
deleted
deploymentcreated
deployment_protection_rulerequested
deployment_reviewapproved
rejected
requested
deployment_statuscreated
discussionanswered
category_changed
closed
created
deleted
edited
labeled
locked
pinned
reopened
transferred
unanswered
unlabeled
unlocked
unpinned
discussion_commentcreated
deleted
edited
fork
github_app_authorizationrevoked
gollum
installationcreated
deleted
new_permissions_accepted
suspend
unsuspend
installation_repositoriesadded
removed
installation_targetrenamed
issue_commentcreated
deleted
edited
issuesassigned
closed
deleted
demilestoned
edited
labeled
locked
milestoned
opened
pinned
reopened
transferred
typed
unassigned
unlabeled
unlocked
unpinned
untyped
labelcreated
deleted
edited
marketplace_purchasecancelled
changed
pending_change
pending_change_cancelled
purchased
memberadded
edited
removed
membershipadded
removed
merge_groupchecks_requested
destroyed
metadeleted
milestoneclosed
created
deleted
edited
opened
org_blockblocked
unblocked
organizationdeleted
member_added
member_invited
member_removed
renamed
packagepublished
updated
page_build
personal_access_token_requestapproved
cancelled
created
denied
ping
projectclosed
created
deleted
edited
reopened
project_cardconverted
created
deleted
edited
moved
project_columncreated
deleted
edited
moved
projects_v2closed
created
deleted
edited
reopened
projects_v2_itemarchived
converted
created
deleted
edited
reordered
restored
projects_v2_status_updatecreated
deleted
edited
public
pull_requestassigned
auto_merge_disabled
auto_merge_enabled
closed
converted_to_draft
demilestoned
dequeued
edited
enqueued
labeled
locked
milestoned
opened
ready_for_review
reopened
review_request_removed
review_requested
synchronize
unassigned
unlabeled
unlocked
pull_request_reviewdismissed
edited
submitted
pull_request_review_commentcreated
deleted
edited
pull_request_review_threadresolved
unresolved
push
registry_packagepublished
updated
releasecreated
deleted
edited
prereleased
published
released
unpublished
repositoryarchived
created
deleted
edited
privatized
publicized
renamed
transferred
unarchived
repository_advisorypublished
reported
repository_dispatchsample
repository_import
repository_rulesetcreated
deleted
edited
repository_vulnerability_alertcreate
dismiss
reopen
resolve
secret_scanning_alertcreated
publicly_leaked
reopened
resolved
validated
secret_scanning_alert_locationcreated
secret_scanning_scancompleted
security_advisorypublished
updated
withdrawn
security_and_analysis
sponsorshipcancelled
created
edited
pending_cancellation
pending_tier_change
tier_changed
starcreated
deleted
status
sub_issuesparent_issue_added
parent_issue_removed
sub_issue_added
sub_issue_removed
teamadded_to_repository
created
deleted
edited
removed_from_repository
team_add
watchstarted
workflow_dispatch
workflow_jobcompleted
in_progress
queued
waiting
workflow_runcompleted
in_progress
requested

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", ...]

validateEventName

The functionvalidateEventName asserts that the provided event name is a valid event name or event/action combination.It throws an error if the event name is not valid, or '*' or 'error' is passed.

The second parameter is an optional options object that can be used to customize the behavior of the validation. You can setaonUnknownEventName property to"warn" to log a warning instead of throwing an error, and alog property to provide a custom logger object, which should have a"warn" method. You can also setonUnknownEventName to"ignore" to disable logging or throwing an error for unknown event names.

import{validateEventName}from"@octokit/webhooks";validateEventName("push");// no errorvalidateEventName("invalid_event");// throws an errorvalidateEventName("*");// throws an errorvalidateEventName("error");// throws an errorvalidateEventName("invalid_event",{onUnknownEventName:"warn"});// logs a warningvalidateEventName("invalid_event",{onUnknownEventName:false,log:{warn:console.info,// instead of warning we just log it via console.info},});validateEventName("*",{onUnkownEventName:"ignore"});// throws an errorvalidateEventName("invalid_event",{onUnkownEventName:"ignore"});// no error, no warning

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 useconditional exports, you will need to adapt yourtsconfig.json by setting"moduleResolution": "node16", "module": "node16".

See the TypeScript docs onpackage.json "exports".
See thishelpful guide on transitioning to ESM from@sindresorhus

⚠️ Caution⚠️: Webhooks Types are expected to be used with thestrictNullChecks option enabled in yourtsconfig. If you don't have this option enabled, there's the possibility that you getnever as the inferred type in some use cases. Seeoctokit/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 anid,name, andpayload properties.An optional generic parameter can be passed to narrow the type of thename andpayload properties based on event names or event/action combinations, e.g.EmitterWebhookEvent<"check_run" | "code_scanning_alert.fixed">.

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp