Auto-pull GitHub repo via Webhook on VPS

Auto-pull GitHub repo via Webhook on VPS

Table of contents

No heading

No headings in the article.

Webhooks are automated messages sent when something happens. Certain actions performed on a GitHub repo like push, pull request, star, etc. can trigger a webhook i.e. send a message about the occurred event.

My portfolio and resume are hosted on my VPS, every time I made some changes in my resume latex, I had to manually login into the server and update the PDF.

To automate this, I set up a GitHub action that compiles my updated Latex into PDF and commits the PDF into the repo.

Now to auto-fetch the new PDF on the server, I wrote an Express API in TypeScript that takes a pull of the repo.

Following is its code

import express, {Application, Request, Response, NextFunction} from 'express';
import {resolve} from 'node:path';
import {execSync} from 'child_process';

//Express App
const app: Application = express();

//Webhook endpoint.
//Get's triggered by GitHub webhook
app.post('/',(req: Request,res: Response)=>{

    cloneRepo();

    res.send('Pulled the repo');
})

//Server listening on port 5000
app.listen(5000, ()=>{
    console.log("Server Running on port 5000");
})

//Function to execute the git pull shell command
const cloneRepo = ()=>{
    execSync('git pull origin main', {
        stdio: [0, 1, 2], 
        cwd: resolve(__dirname, '../../resume-files'),
      })
}

The API gets triggered by GitHub when a push is made to my repo and it executes a shell command that pulls the changes from the source repo.

The snippet can be customized to perform any action.

Started it in the background using PM2 and it works perfectly.

Note: I've used NGINX as a reverse proxy to expose the API to the internet.

Did you find this article valuable?

Support Wilfred Almeida by becoming a sponsor. Any amount is appreciated!