A simple example of using Node.js to send Growl-style messages to a browser via Socket.IO.
📌 Available on Docker Hub: hendridm/socketio-relay
The server does one thing: It accepts JSON data submitted to the endpoint and forwards it to the specified socket. It will relay any data that you submit - it is up to the listening client to consume it.
You can have any number of clients listening to different sockets. In this way, you can have multiple apps listening for different events and different payloads. Purely as examples, you could have all of the following:
- An admin panel that listens on a socket named
admin-notifications
, receiving information about system events. - An e-commerce site that listens on a socket named
sales-popups
, which displays a sale notification to visitors, similar to Sales Pop. - A real-time chat application that listens on a socket named
chat-app
, which broadcasts user messages as they are submitted.
These are just examples - you can relay any data to any number of sockets that you wish. The included demo page is simply an example of consuming data received from the server. Your usage will vary.
- Add simple Growl-style example
- Add advanced example with custom template and image
- Improve input validation
- Improve exception handling
- WordPress plugin and integrations
To install, clone the repository, install dependencies and start the server:
git clone https://github.com/dmhendricks/nodejs-simple-message-relay.git
cd nodejs-simple-message-relay
npm install
npm run start
📌 For local development, you can use npm run dev
instead to automatically reload the server as you modify and save files.
- Visit http://localhost:3000/ in your web browser to bring up the client-side browser demo (disabled if
demo_page
is false in config). - Use Postman or cURL to send a POST to the
/send
endpoint:
Send a Simple Notification
curl -X POST 'http://localhost:3000/send/my-socket-name?api_key=YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"message": "Hello world!",
"color": "info"
}'
Send an Advanced Notification
curl -X POST 'http://localhost:3000/send/my-socket-name?api_key=YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"type": "advanced",
"message": "Someone in Chicago, USA just bought a <strong>Toolbox Widget/Modular Toolbox Wrench Organizer</strong>!",
"link": "https://smile.amazon.com/dp/B07H6FJY9D/",
"image": "https://picsum.photos/id/237/200/200"
}'
After sending one or more messages, they should appear on the browser demo page. See public/index.html
for source code.
Note: The api_key
query string variable may be absent in development mode (ie, when NODE_ENV
is not defined).