PieSocket logo

Publish with JavaScript & NodeJS

NodeJS is used on the server-side while Javascript can be used in the browser to publish a message.

Publish with NodeJS

Use the following code snippet to publish a message on a WebSocket channel with NodeJS.

var unirest = require('unirest');

var payload = {
    "key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", //Demo key, get yours at https://piesocket.com
    "secret": "d8129f82f8dd71910aa4a7efa30a7297", //Demo secret, get yours at https://piesocket.com
    "channelId": 1,
    "message": { "text": "Hello world!" }

var req = unirest('POST', 'https://www.piesocket.com/api/publish')
        'Content-Type': 'application/json'
    .end(function(res) {
        if (res.error) throw new Error(res.error);

This sends a JSON message to channel 1, to send a string, replace "message": { "text": "Hello world!" } with "message": "Hello world!"

Publish with Javascript in Browser

There are two possible ways to publish with JavaScript in the browser.

1. Using the WebSocket client

var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm'; //Demo key, Change this to yours
var channelId = 1; 
var piesocket = new WebSocket(`wss://demo.websocket.me/v3/${channelId}?api_key=${apiKey}&notify_self`);

piesocket.send("Hello world!");

You need to enable C2C (client-to-client) communications for your API, for this to work. You can manage your C2C settings in your PieSocket account

2. Using XHR/Ajax requests

{warning} Publishing with frontend code is not secure, doing this will compromise your API secret

var data = JSON.stringify({"key":"oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm","secret":"d8129f82f8dd71910aa4a7efa30a7297","channelId":1,"message":"Hello world!"});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {

xhr.open("POST", "https://www.piesocket.com/api/publish");
xhr.setRequestHeader("Content-Type", "application/json");


Please note that this example uses a demo key and secret, which is public. The demo key is only for quick testing purposes, and you should not use this in your application.

You can get your free API key and API secret here.


Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.