|

|  How to Receive Webhook Notifications from GitHub API in Node.js

How to Receive Webhook Notifications from GitHub API in Node.js

October 31, 2024

Learn how to set up and receive GitHub webhook notifications in Node.js effectively. Step-by-step guide with practical examples to enhance your development process.

How to Receive Webhook Notifications from GitHub API in Node.js

 

Set Up Your Node.js Environment

 

  • Ensure Node.js and npm are installed on your machine. You can verify this by running node -v and npm -v in your terminal.
  •  

  • Create a new project directory and initialize it with npm init -y to generate a package.json file. This step allows you to manage your dependencies effectively.
  •  

  • Install Express, which will help in setting up a server to receive webhook notifications, using the command: npm install express.

 

Create an Express Server

 

  • Within your project directory, create a new file named server.js and set up a simple Express server to listen to incoming requests from GitHub.
  •  

    const express = require('express');
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.use(express.json());
    
    app.post('/webhook', (req, res) => {
      console.log('Webhook received!', req.body);
      res.status(200).send('OK');
    });
    
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    

     

  • The app.use(express.json()) middleware is crucial here as GitHub sends the webhook data as JSON.

 

Setup a Public URL

 

  • Since GitHub needs a publicly accessible URL to send the webhook data, we can use a tunneling service like ngrok or serveo to expose our local server to the internet.
  •  

  • For ngrok, download and install it, then run ngrok http 3000 to create a tunnel to your local server.
  •  

  • Note the provided public URL, as it will be needed when setting up the webhook on GitHub.

 

Configure GitHub Webhook

 

  • Navigate to the repository on GitHub where you want to set up the webhook.
  •  

  • Go to the repository's settings page and select "Webhooks" from the sidebar.
  •  

  • Click "Add webhook" and paste the public URL from your ngrok or Serveo output, appending /webhook (e.g., https://your-ngrok-url/webhook).
  •  

  • Select the events you want to receive, or choose to get notifications for everything.
  •  

  • Make sure the content type is set to application/json.
  •  

  • Click "Add webhook" to finalize.

 

Verify Webhook Receiving

 

  • Trigger an event on your GitHub repository that you set the webhook for, such as pushing a commit or opening a pull request.
  •  

  • Check your terminal where the Node.js app is running. You should see output from console.log('Webhook received!', req.body); with the JSON payload from GitHub.
  •  

  • If no output appears, revisit the setup steps to ensure everything is configured correctly, and check the webhook delivery status on GitHub for any errors.

 

Enhance Webhook Security

 

  • Consider setting a secret when configuring the webhook in GitHub for an extra layer of security.
  •  

  • Modify your Express server to verify this secret by comparing it to a hash from the incoming request header. Use a suitable library such as crypto.

 

const crypto = require('crypto');

// Replace 'your_secret' with the same secret configured in your webhook settings
const secret = 'your_secret';

app.post('/webhook', (req, res) => {
  const hmac = crypto.createHmac('sha256', secret);
  const digest = 'sha256=' + hmac.update(JSON.stringify(req.body)).digest('hex');
  const checksum = req.headers['x-hub-signature-256'];
  
  if (checksum === digest) {
    console.log('Webhook received and verified!', req.body);
    res.status(200).send('Verified!');
  } else {
    console.error('Webhook signature verification failed.');
    res.status(400).send('Verification failed!');
  }
});

 

  • This script will ensure that only requests from GitHub are processed, enhancing security.