On this page

Functions v1 Development Guidelines

Functions API

For the Functions v1 API, see the Functions API docs.

Introduction

This page shows how to run Functions v1 after you create and configure them. For an overview, see Functions v1 Basics.

  • PubNub provides integrations through the Integration Catalog.
  • Functions are JavaScript modules with a default export Function. See guidelines for each event type.
  • PubNub provides modules to help you develop Functions.
  • Asynchronous operations use Promises. See Promises.
  • You can chain up to 3 Functions to run in sequence. See Chaining.

Development guidelines

Code structure

For all event types except On Request, use this structure:

1export default (request) => {
2 // Your business logic here
3 return request.ok();
4 // request.abort(); to fail execution
5};

For all event types except On Request and On Interval, the request object has two methods: ok() and abort(). The response object isn’t available. For details, see On Request and On Interval.

On Request

Use this structure:

1export default (request, response) => {
2 // Your code here
3 return response.send();
4};

For On Request, the request object has json(), and the response object has send(). For details, see On Request Inputs/Outputs.

On Interval

Use this structure:

1export default (event) => {
2 // Your code here
3 return event.ok();
4};

For On Interval, the event object has ok(). For details, see On Interval Inputs/Outputs.

Promises

Asynchronous operations use Promises (ES6). promise is implicitly available for every Function.

1const Promise = require('promise'); // No need to add this line
Learn more

Promise.all()

Use Promise.all() to run multiple async calls in parallel.

Example: fetch a user name from KV Store and an IP address from a web service. When both resolve, update the request.

1export default (request) => {
2 const store = require('kvstore');
3 const xhr = require("xhr");
4
5 const fullName = store.get('fullName');
6 const ipAddress = xhr.fetch("https://httpbin.org/ip");
7
8 return Promise.all([fullName, ipAddress])
9 .then((values) => {
10
11 request.message.fullNameResult = values[0];
12 request.message.ip = JSON.parse(values[1].body).origin;
13
14 return request.ok();
15 })
show all 20 lines

Modules

The Functions runtime provides built‑in modules to extend JavaScript and improve performance.

Functions API

For the Functions v1 API, see the Functions API docs.

Import a library with require():

1const xhr = require('xhr'); // Example import

Common modules:

Library NameDescription
XHR
Send HTTP/HTTPS requests and load responses. Useful for third‑party auth or triggering webhooks.
KV Store
Persistent key‑value store shared at the Subscribe Key level.
Advanced Math
Global coordinate and geometry functions.
Crypto
Encrypt and decrypt data in a Function.
Utils
Utility helpers.
Codec/auth
Encode HTTP Basic Auth credentials.
Codec/base64
Encode and decode Base64 strings.
Codec/query_string
Encode and decode URI query parameters.
PubNub
Use many client SDK features from a Function.
Vault
Read‑only secrets storage.
Features not available in Functions v1

Some JavaScript features aren’t available in Functions v1:

  • Native Node modules
  • async/await
  • Access to process and some other globals
  • Installing third‑party modules via npm

Webhooks on request

You can use an On Request event type to create webhooks.

Example: check if a username exists. Assume username is passed as a query parameter.

  1. Extract the username and check the KV store. Create the user if missing.

    1export default (request, response) => {
    2
    3 const db = require('kvstore');
    4 const username = request.params.username;
    5
    6 return db.get(username).then((dataFromDb) => {
    7 if (!dataFromDb) {
    8 console.log('The username does not exist.');
    9 db.set(username, {});
    10 response.status = 200;
    11 return response.send('Username is available');
    12 } else {
    13 console.log('The username already exists.');
    14 response.status = 409;
    15 return response.send('Username already exists');
    show all 18 lines
  2. Click Save, then Restart Module.

Now test the Function from the HTTP client on the left.

Chaining

Functions can run in sequence or based on a condition. Use pubnub.publish(), pubnub.signal(), or pubnub.triggerRequestFunction().

Modules for chained Functions

Place Functions you plan to chain in the same Module. It’s easier to start/stop them.

Chain Functions

Example: capture messages on hello-world and send them to the hello-logger Function.

  1. Create an On Before Publish or Fire hello-logger Function:

    1export default (request) => {
    2 console.log(request) // show what we have inside
    3 return request.ok() // done
    4};
  2. Create an On Before Publish or Fire hello-world Function:

    1export default (request) => {
    2 const pubnub = require('pubnub');
    3
    4 pubnub.publish({
    5 "channel": "hello-logger",
    6 "message":request.message
    7 }).then((publishResponse) => {
    8 console.log(`Publish Status: ${publishResponse[0]}:${publishResponse[1]} with TT ${publishResponse[2]}`);
    9 }).catch((err) => {
    10 console.error(err);
    11 });
    12
    13 return request.ok(); // Return a promise when you're done
    14};
  3. Click Save.

  4. Click Restart Module.

  5. Open PubNub Debug Console.

  6. Enter hello_world, hello-logger for the channel. Click Subscribe.

  7. Back on the Functions screen, click Publish on the test payload.

Fork Functions

Example: capture messages on hello-world, add "Hello": "World", and publish to hello-universe and hello-world.

  1. Create a new Before Publish or Fire Function:

    1export default (request) => {
    2 const db = require('kvstore');
    3 const pubnub = require('pubnub');
    4
    5 console.log('The message ', request.message, ' was published on ', request.channels[0], ' via ', request.meta.clientip);
    6
    7 request.message.hello = 'world!'; // augment hello = world
    8
    9 // To fork return pubnub.publish and include request.ok in the .then()
    10 return pubnub.publish({
    11 "channel": "hello_universe",
    12 "message": request.message
    13 }).then((publishResponse) => {
    14 console.log(`Publish Status: ${publishResponse[0]}:${publishResponse[1]} with TT ${publishResponse[2]}`);
    15 return request.ok();
    show all 31 lines
  2. Click Save.

  3. Click Restart Module.

  4. Open PubNub Debug Console.

  5. Enter hello-world, hello-universe for the channel. Click Subscribe.

  6. Back on the Functions screen, click Publish on the test payload.

Avoid infinite loops

Design chains and forks to be loop‑free (for example, A → B → C). The platform includes loop protection; build logic that remains loop‑free.

Recursion limit

The maximum recursion limit is 3 hops from one Function to another. Using publish or fire, you can execute at most three Functions.

Within a single Function execution, the combined maximum number of KV store operations, XHRs, publish, and fire is 3.

Request/Response objects

All event types except On Request

request methods

MethodArgumentsDescription
ok
message:String (Optional)
Returns a promise that resolves to the value of the request object.
abort
message:String (Optional)
Returns a promise that resolves to the value of the request object, with an error code.

request attributes

AttributeTypeDefinition
message
Object
The actual user message sent to the channel.
verb
String
Method used by the publishing client when sending the message to PubNub.
pubkey
String
The Publish Key used when sending the message.
subkey
String
The Subscribe Key to retrieve the message.
channels
Array<String>
The list of channels on which the message was sent.
version
String
API Version.
meta.clientip
String
IP of the publishing client.
meta.origin
String
Origin defined on the publishing client.
meta.useragent
String
The publishing client's user agent string.
params
Object
URL parameters on the request.
uri
String
The request URI.

On Request Inputs/Outputs

request attributes

AttributeTypeDefinition
verb
String
Method used by the publishing client when sending the message to PubNub. Always set to rest.
pubkey
String
The Publish Key used when sending the message.
subkey
String
The Subscribe Key to retrieve the message.
version
String
API Version.
meta.clientip
String
IP of the publishing client.
meta.origin
String
Origin defined on the publishing client.
meta.useragent
String
The publishing client's user agent string.
params
Object
URL parameters on the request.
uri
String
The full path of the URI minus PubNub hostname information.
path
String
The path minus PubNub and key information. This is the path you configured for the Function.
method
String
HTTP method such as GET, PUT, POST, DELETE.
body
Object
The body content if passed in the request.
headers
Object
Header information passed in the request.

response methods

MethodArgumentsDescription
send
body:String (Optional)
Returns a promise that resolves to the value of the response object.
response attributes
AttributeTypeDefinition
status
Object
HTTP status code returned to the caller.
body
Object
Response body returned to the caller.
headers
Object
Response headers returned to the caller.

On Interval Inputs/Outputs

event methods

MethodArgumentsDescription
ok
N/A
Returns a promise that resolves to the value of the response object.

event attributes

AttributeTypeDefinition
verb
String
Method used by the publishing client when sending the message to PubNub. Always set to interval.
pubkey
String
The Publish Key used when sending the message.
subkey
String
The Subscribe Key to retrieve the message.
execInterval
Number
Duration of the interval in milliseconds.
lastTimestamp
Number
Timestamp of last Function execution.
timestamp
Number
Timestamp of current Function execution.

Subscribe on Interval Inputs/Outputs

event methods

MethodArgumentsDescription
ok
N/A
Returns a promise that resolves to the value of the response object.

event attributes

AttributeTypeDefinition
verb
String
Method used by the publishing client when sending the message to PubNub. Always set to interval.
pubkey
String
The Publish Key used when sending the message.
subkey
String
The Subscribe Key to retrieve the message.
execInterval
Number
Duration of the interval in milliseconds.
lastTimestamp
Number
Timestamp of last Function execution.
timestamp
Number
Timestamp of current Function execution.

Create a Function

Follow these instructions to create a Function.

Admin Portal UI

This section shows how to use the Admin Portal to create PubNub Functions v1. To learn the Functions v1 UI, see Functions v1.

Hello World

Create a Module before you create a Function. A Module is a collection of Functions. Modules let you start and stop a set of Functions together.

  1. Log in to the Admin Portal. Go to FunctionsCreate New ModuleCreate New Function → select Before Publish or Fire. For event types, see Event Types.

  2. Set the trigger channel to hello-world. Click Save.

  3. A sample Function appears. Replace the code to add simple logging.

    1export default (request) => {
    2
    3 console.log('request', request);
    4 request.message.hello = 'world!'; // augment hello = world
    5 console.log('The message: ', request.message, ' was published on ', request.channels[0], ' via', request.meta.clientip);
    6
    7 return request.ok(); // Return a promise when you're done
    8}
  4. Click Save Function on the left panel.

Run & test

  1. Start the Module.
  2. Click Publish in Test payload to run the Function.

Trigger Functions

A Function triggers on one or more channels, except On Request, which triggers via HTTP request. Clients on a channel don’t know which Functions run. A Function runs only when its parent Module is running.

Start a Module

Click Start Module at the top right of the Functions screen.

Starting a Module schedules the latest saved version of each Function within seconds. Click Save first to ensure you run the latest code.

When the Module starts, each Function runs on all PubNub data centers until you stop the Module. All Functions run hot for low latency.

Stop a Module

Click Stop Module at the top right of the Functions screen.

When stopped, all Functions in the Module stop. Messages pass through the PubNub Network without triggering Functions. Web API calls to On Request Functions return 404 Not Found.

Module states

StateDefinition
Stopped
No Functions are running. Messages pass through the PubNub Network without triggering Functions.
Running
All Functions in the Module are running.
Pending
Functions are starting. This transient state can last up to 20 seconds.
Stopping
Functions are stopping. This transient state can last a few seconds.
Failed
One or more Functions encountered an error; the Module stopped all Functions to protect execution. Check logs for details.
Last updated on