1

I am building a headless CMS with Strapi. I am testing the webhooks section and want to show the received data from the webhook on my React front-end.

I created a new folder webhooks on my local machine and ran npm init -y. It created a package.json file with this content in it:

{
  "name": "webhooks",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

I added a index.js file to the root folder with this content and installed express and body-parser:

const express = require("express")
const bodyParser = require("body-parser")

const app = express()
const PORT = 3001

app.use(bodyParser.json())
app.post("/webhook", (req, res) => {
  console.log(req.body)
  res.status(200).end()
})

app.listen(PORT, () => console.log(` Server running on port ${PORT}`))

After that I added this line in my package.json:

"start": "node index.js"

So it will start up with npm start instead of node index.js.

I added this URL to my strapi webhooks: http://localhost:3001/webhook and tested the trigger from the Strapi admin. It works fine.

After this I ran npx create-react-app client to create my react front-end app.

My next question is now how can I receive the contents from the webhook in my react front-end app?

Gery
  • 13
  • 4

1 Answers1

0

I am trying to do the same thing and I found that you need to basically use web sockets to establish a two way connection between your front-end and back-end. This way, when the back-end receives the notification, it will then notify your front-end.

Similar SO question with a good answer with some code: How to use an API webhook in React to receive notifictions

Note, it shows how to listen to an event on the front-end using standard JS but you could use a library like Socket IO. This guide is really good for using SocketIO with a React app.To trigger the event from the server, you can use the same library and emit an event after doing the console.log in the /webhook route. Just take a look at the Socket IO docs, it's pretty simple.

In the Broadcasting section, they show how to broadcast from the server to all connected clients:

io.emit('yourEventName', { someProperty: 'some value', otherProperty: 'other value' }); // This will emit the event to all connected sockets

On the client, after importing socket.io.js you can:

var socket = io();

socket.on('yourEventName', function(msg) {
console.log(msg);
});

For Vercel users: you can listen to a websocket but you cannot be the websocket server, you can google it, so you need an alternative solution that handles websockets for you like PubNub or Pusher, or change hosting.

iBobb
  • 1,140
  • 1
  • 14
  • 35