
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
@octokit/webhooks
Advanced tools
@octokit/webhooks is a Node.js library for handling GitHub webhooks. It provides a simple and efficient way to listen for and respond to GitHub webhook events, making it easier to integrate GitHub with your applications.
Webhook Event Handling
This feature allows you to handle specific GitHub webhook events, such as 'push'. The code sample demonstrates setting up a webhook listener for 'push' events and starting an HTTP server to listen for incoming webhook requests.
const { Webhooks } = require('@octokit/webhooks');
const webhooks = new Webhooks({ secret: 'mysecret' });
webhooks.on('push', ({ id, name, payload }) => {
console.log(name, 'event received');
console.log('Payload:', payload);
});
require('http').createServer(webhooks.middleware).listen(3000);
Webhook Signature Verification
This feature allows you to verify the signature of incoming webhook requests to ensure they are from GitHub. The code sample demonstrates how to verify a webhook signature using a secret.
const { verify } = require('@octokit/webhooks');
const payload = JSON.stringify({ foo: 'bar' });
const signature = 'sha256=abcdef1234567890';
const secret = 'mysecret';
const isValid = verify(secret, payload, signature);
console.log('Signature is valid:', isValid);
Webhook Event Routing
This feature allows you to route different webhook events to specific handlers. The code sample demonstrates setting up a general event handler for all events and a specific handler for 'issues.opened' events.
const { Webhooks } = require('@octokit/webhooks');
const webhooks = new Webhooks({ secret: 'mysecret' });
webhooks.on('*', ({ id, name, payload }) => {
console.log(`Received event: ${name}`);
});
webhooks.on('issues.opened', ({ id, name, payload }) => {
console.log('Issue opened:', payload.issue.title);
});
require('http').createServer(webhooks.middleware).listen(3000);
express-github-webhook is a lightweight middleware for Express.js to handle GitHub webhooks. It is simpler and more focused on Express.js integration compared to @octokit/webhooks, which offers a broader range of features and integrations.
node-github-webhook is a basic Node.js library for handling GitHub webhooks. It provides a straightforward way to listen for webhook events but lacks some of the advanced features and flexibility of @octokit/webhooks.
github-webhook-handler is a Node.js library for handling GitHub webhooks. It is similar to @octokit/webhooks in terms of functionality but is more minimalistic and does not offer the same level of integration and additional features.
GitHub webhook events toolset for Node.js
GitHub webhooks can be registered in multiple ways
@octokit/webhooks
helps to handle webhook events received from GitHub.
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.
// install with: npm install @octokit/webhooks
const WebhooksApi = require('@octokit/webhooks')
const webhooks = new WebhooksApi({
secret: 'mysecret'
})
webhooks.on('*', ({id, name, payload}) => {
console.log(name, 'event received')
})
require('http').createServer(webhooks.middleware).listen(3000)
// can now receive webhook events at port 3000
new WebhooksApi({secret[, path]})
secret
(String)
| Required. Secret as configured in GitHub Settings. |
transform
(Function)
|
Only relevant for webhooks.on .
Transform emitted event before calling handlers. Can be asynchronous.
|
path
(String)
|
Only relevant for webhooks.middleware .
Custom path to match requests against. Defaults to / .
|
Returns the webhooks
API.
weebhooks.sign(eventPayload)
eventPayload
(Object)
| Required. Webhook request payload as received from GitHub |
Returns a signature
string. Throws error if eventPayload
is not passed.
Can also be used standalone.
weebhooks.verify(eventPayload, signature)
eventPayload
(Object)
| Required. Webhook event request payload as received from GitHub. |
signature
(String)
|
Required.
Signature string as calculated by webhooks.sign() .
|
Returns true
or false
. Throws error if eventPayload
or signature
not passed.
Can also be used standalone.
weebhooks.verifyAndReceive({id, name, payload, signature})
id
String
| Unique webhook event request id |
name
String
|
Required.
Name of the event. (Event names are set as X-GitHub-Event header
in the webhook event request.)
|
payload
Object
| Required. Webhook event request payload as received from GitHub. |
signature
(String)
|
Required.
Signature string as calculated by webhooks.sign() .
|
Returns a promise.
Verifies event using webhooks.verify(), then handles the event using webhooks.receive().
Additionally, if verification fails, rejects return promise and emits an error
event.
Example
const WebhooksApi = require('@octokit/webhooks')
const webhooks = new WebhooksApi({
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-github-signature']
}).catch(handleErrorsFromHooks)
webhooks.receive({id, name, payload})
id
String
| Unique webhook event request id |
name
String
|
Required.
Name of the event. (Event names are set as X-GitHub-Event header
in the webhook event request.)
|
payload
Object
| Required. Webhook event request payload as received from GitHub. |
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 receiver module which can be used standalone.
webhooks.on(eventName, handler)
webhooks.on(eventNames, handler)
eventName
String
| Required. Name of the event. One of GitHub’s supported event names. |
eventNames
Array
| Required. Array of event names. |
handler
Function
|
Required.
Method to be run each time the event with the passed name is received.
the handler 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 the receiver module which can be used standalone.
webhooks.removeListener(eventName, handler)
webhooks.removeListener(eventNames, handler)
eventName
String
| Required. Name of the event. One of GitHub’s supported event names. |
eventNames
Array
| Required. Array of event names. |
handler
Function
|
Required.
Method which was previously passed to webhooks.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 the receiver module which can be used standalone.
webhooks.middleware(request, response[, next])
request
Object
| Required. A Node.js http.ClientRequest. |
response
Object
| Required. A Node.js http.ServerResponse. |
next
Function
| Optional function which invokes the next middleware, as used by Connect and Express. |
Returns a requestListener
(or middleware) method which can be directly passed to http.createServer()
, Express and other compatible Node.js server frameworks.
Can also be used standalone.
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 |
---|---|
commit_comment
|
.created
|
create
| |
delete
| |
deployment
| |
deployment_status
| |
fork
| |
gollum
| |
installation
|
.created .deleted
|
installation_repositories
|
.added .removed
|
issue_comment
|
.created .edited .deleted
|
issues
|
.assigned .unassigned .labeled .unlabeled .opened .edited .milestoned .demilestoned .closed .reopened
|
label
|
.created .edited .deleted
|
marketplace_purchase
|
.purchased .cancelled .changed
|
member
|
.added .edited .deleted
|
membership
|
.added .removed
|
milestone
|
.created .closed .opened .edited .deleted
|
org_block
|
.blocked .unblocked
|
organization
|
.member_added .member_removed .member_invited
|
page_build
| |
ping
| |
project
|
.created .edited .converted .moved .deleted
|
project_card
|
.created .edited .closed .reopened .deleted
|
project_column
|
.created .edited .moved .deleted
|
public
| |
pull_request
|
.assigned .unassigned .review_requested .review_request_removed .labeled .unlabeled .opened .edited .closed .reopened .synchronize
|
pull_request_review
|
.submitted .edited .dismissed
|
pull_request_review_comment
|
.created .edited .deleted
|
push
| |
release
|
.published
|
repository
|
.created .deleted .archived .unarchived .publicized .privatized
|
status
| |
team
|
.created .deleted .edited .added_to_repository .removed_from_repository
|
team_add
| |
watch
|
.started
|
Besides the webhook events, there are special events emitted by @octokit/webhooks
.
*
wildcard eventThe *
event is emitted for all webhook events listed above.
webhooks.on('*', (event) => {
console.log(`"${event.name}" event received"`)
})
error
eventIf a webhook event handler throws an error or returns a promise that rejects, an error
event is triggered. You can subscribe to this event for logging or reporting events. The passed error
object has a .event
property which has all information on the event:
id
: The unique webhook event request idname
: The name of the eventpayload
: The event request payloadwebhooks.on('error', (error) => {
console.log(`Error occured in "${error.event.name} handler: ${error.stack}"`)
})
Asynchronous error
event handler are not blocking the .receive()
method from completing.
FAQs
GitHub webhook events toolset for Node.js
The npm package @octokit/webhooks receives a total of 1,328,485 weekly downloads. As such, @octokit/webhooks popularity was classified as popular.
We found that @octokit/webhooks demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.