Search code examples
javascriptdeploymentvercelably-realtime

Vercel ably setup


I am new to vercel and I am trying to deploy an application which consist of chat feature. I am using ably.com as pub/sub chat feature. I am trying to use ably realtime for both publishing and subscribing the event but somehow the publish event in API throws an error. I checked the documentation and I coded it correctly.

The same code is working perfectly fine on localhost but as soon as I deploy that to vercel then it does not work and throw error.

I am using following code to publish the message from API.

var realtime = new Ably.Realtime('<Ably key>');
var channel = realtime.channels.get('ham-gym-tag');
channel.publish('example', 'message data');

Solution

  • I faced a similar issue during my deployment. The catch here is to use ABLY REST API (https://www.ably.io/documentation/rest) to send/publish a message and ABLY Realtime for subscribing for events. In this way, you even do not need to write an API. You can directly call the Ably REST API via Axios or similar npm package.

    Call the following method to send/publish the message to ABLY

    const onSave = async () => {
    let data = { name: "greeting", data: msg };
    const res = await axios({
      method: "POST",
      headers: {
        Authorization:
          "Basic " + new Buffer(process.env.ABLY_CLIENT_ID).toString("base64"),
        "Content-Type": "application/json",
      },
      url: "https://rest.ably.io/channels/<channel name>/messages",
      data: data,
    });
    };
    

    Please note you have to replace the with your channel name and ABLY_CLIENT_ID with your ABLY client id. In the above code 'name: "Greeting"' defines the event name on which you will publish the message. Now you can write the following code in the file where you want to subscribe for the event "greeting"

    useEffect(() => {
    var ably = new Ably.Realtime(process.env.ABLY_CLIENT_ID);
    const channelAbly = ably.channels.get(<channl name>);
    channelAbly.subscribe("greeting", function (message) {
      // console.log("message received for event " + message.name);
      // console.log("message data:" + message.data);
    });
    }, []);
    

    Please note you have to replace the with your channel name and ABLY_CLIENT_ID with your ABLY client id. Also please change the even name from "Greeting" to something else if you want.

    The above code will be fired whenever a new message is published to the channel with event "greeting".