Add event-driven business logic
Sending and receiving messages is the foundation of PubNub, but it's only the beginning. Once you can send messages, you may ask: What else can I do with messages? This is where Functions help.
Before you begin, make sure you have a PubNub account and an active keyset. See account setup and keysets for details.
Functions are JavaScript that run before or after events in your PubNub environment. You can also schedule Functions or trigger them via external requests. Functions are event‑driven, so you focus on the code.
To create a Function, go to the Admin Portal, select your keyset, and open Functions. Enter a name and description, then select Create Package.
Choose to create a custom Function from scratch, or import a prebuilt Function from a third‑party provider such as AWS Lambda, Twitter webhooks, Stripe, or Mapbox.
Let's create your own Function.
Select Create function. Enter a name and choose “Before fire” for now. Many options exist—learn more about Functions. In the channel field, enter the channel to run this code against, then select Create.
This example catches a message and modifies it by adding extra text.
export default (request) => {
console.log(request.message.text); //This is the message being sent
var updateMessage = request.message.text + "... And a little bit more" //adding some text to the message
request.message.text = updateMessage;
console.log("message:",request.message.text); //This is the updated message
return request.ok(); // returns
};
Return outcomes (for context):
return request.ok()
sends a success response to the client.return false
blocks the message from being published.- Returning a modified object lets you change the message before publish.
Save your Function. Select Start module, then Publish your test payload. The text updates to include the extra string.
This simple example is a starting point. Common use cases include:
- Announcing to a channel when someone joins or leaves
- Sending a notification when an IoT device goes down
- Sending a push notification when a user enters or leaves a geofenced area
- Connecting users to chatbots
- Collecting aggregate data from sensors for dashboard analytics
- Triggering backups
You can also add Language Translation, SMS, or profanity filtering from third‑party services, or even chain Functions together. Unlike generic messaging platforms, PubNub Functions provide serverless logic on the same real‑time network—no separate infrastructure required.
Being able to control actions in your PubNub environment makes PubNub unique. Functions add flexible ways to build applications.
If you’re building for mobile, see set up mobile push notifications.