What is @octokit/webhooks?
@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.
What are @octokit/webhooks's main functionalities?
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);
Other packages similar to @octokit/webhooks
express-github-webhook
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
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
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.
@octokit/webhooks
GitHub webhook events toolset for Node.js

@octokit/webhooks
helps to handle webhook events received from GitHub.
GitHub webhooks can be registered in multiple ways
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
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);
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
- enter it in the GitHub App’s "Webhook URL" input
- pass it to the EventSource constructor, see below
const webhookProxyUrl = "https://smee.io/IrqK0nopGAOc847";
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
Constructor
new Webhooks({ secret });
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.
|
log
object
|
Used for internal logging. Defaults to console with debug and info doing nothing.
|
Returns the webhooks
API.
webhooks.sign()
webhooks.sign(eventPayload);
eventPayload
(String)
|
Required.
Webhook request payload as received from GitHub
|
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);
eventPayload
(String)
|
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.
The verify
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
String
|
Required.
Name of the event. (Event names are set as X-GitHub-Event header
in the webhook event request.)
|
payload
String
|
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 the returned promise and emits an error
event.
Example
import { Webhooks } from "@octokit/webhooks";
const webhooks = new Webhooks({
secret: "mysecret",
});
eventHandler.on("error", handleSignatureVerificationError);
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 });
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 event-handler
module which can be used standalone.
webhooks.on()
webhooks.on(eventName, handler);
webhooks.on(eventNames, handler);
eventName
String
|
Required.
Name of the event. One of GitHub'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
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 event-handler
module which can be used standalone.
webhooks.onAny()
webhooks.onAny(handler);
handler
Function
|
Required.
Method to be run each time any event 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 .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.
handler
Function
|
Required.
Method to be run each time a webhook event handler throws an error or returns a promise that rejects.
The handler 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 the event-handler
module which can be used standalone.
webhooks.removeListener()
webhooks.removeListener(eventName, handler);
webhooks.removeListener(eventNames, handler);
eventName
String
|
Required.
Name of the event. One of GitHub'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 the onAny() method or 'error' for the onError() method.
|
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 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) => {
if (await middleware(req, res)) return;
res.writeHead(404);
res.end();
}).listen(3000);
The middleware returned from createNodeMiddleware
can also serve as an
Express.js
middleware directly.
webhooks
Webhooks instance
|
Required.
|
path
string
|
Custom path to match requests against. Defaults to /api/github/webhooks .
|
log
object
|
Used for internal logging. Defaults to console with debug and info doing nothing.
|
createWebMiddleware()
import { Webhooks, createWebMiddleware } from "@octokit/webhooks";
const webhooks = new Webhooks({
secret: "mysecret",
});
const middleware = createWebMiddleware(webhooks, { path: "/webhooks" });
Deno.serve({ port: 3000 }, middleware);
The middleware returned from createWebMiddleware
can also be used in serverless environments like AWS Lambda, Cloudflare Workers, and Vercel.
webhooks
Webhooks instance
|
Required.
|
path
string
|
Custom path to match requests against. Defaults to /api/github/webhooks .
|
log
object
|
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
.
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;
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