PieSocket Getting Started

PieSocket is a realtime PubSub API, it lets you add WebSocket features like live chat, notifications and presence to your app without running your own WebSocket server. This guide gets you from signup to your first message in a few minutes.

  1. Create an account and get your API key

Create a PieSocket cluster, then open your cluster dashboard to find your apiKey and clusterId. Every SDK needs both to connect.

New accounts come with a demo cluster (apiKey and clusterId: "demo"), so you can follow the steps below immediately, without creating your own cluster first.

  1. Install the SDK

Pick the SDK for your platform.

npm i piesocket-js@7

No SDK for your platform? Connect directly with any WebSocket client using the WebSocket API, or use Laravel Echo if you're already on Laravel broadcasting.

  1. Connect

Initialise the client with your apiKey and clusterId.

import PieSocket from 'piesocket-js';

var pieSocket = new PieSocket({
    version: 4,
    clusterId: "demo",
    apiKey: "YOUR_API_KEY"
});

React Native uses the same piesocket-js API as JavaScript above, just import react-native-get-random-values before piesocket-js in your entrypoint. See the React Native guide for that one extra line.

See the full configuration options for things like ssl, presence and authEndpoint.

  1. Subscribe to a channel

Channels (also called rooms) group connections together, anyone subscribed to the same channel receives its events.

pieSocket.subscribe("chat-room").then((channel) => {
    console.log("Channel is ready");
});

chat-room here is a roomId, any string you choose. You'll reuse the same roomId when publishing from your backend, see choosing a room ID.

  1. Listen for events

channel.listen("new_message", (data, meta) => {
    console.log("New message: ", data);
});

There are also built-in system events, like system:member_joined and system:member_left, useful for presence UIs. See the full list of system events.

  1. Publish an event

Clients can publish directly to each other, this is called client-to-client messaging and is on by default for new clusters.

channel.publish("new_message", {
    from: "Anand",
    message: "Hello PieSocket!"
});

Publish from your backend

Most apps publish from the server instead, after saving to a database or reacting to some other event. Send a POST request to your cluster's REST endpoint:

POST https://CLUSTER_ID.piesocket.com/api/v4/publish

{
  "key": "YOUR_API_KEY",
  "secret": "YOUR_API_SECRET",
  "roomId": "chat-room",
  "message": { "event": "new_message", "data": "Hello from the server!" }
}

See the REST API reference for the full endpoint list, or publish with curl/wget examples if you'd rather script it.

Next steps