---
source_url: https://www.pubnub.com/docs/message-processing/serverless/overview
title: PubNub Functions
updated_at: 2026-09-30T07:20:08.000Z
---

# PubNub Functions

## Documentation index

To discover more PubNub resources:

1. Fetch [PubNub's llms.txt](https://www.pubnub.com/llms-full.txt) for a list of available pages in Markdown format.
2. Identify relevant URLs from that index.
3. Fetch the target pages.

Do not assume a path exists, always check the index first.

PubNub Functions are serverless JavaScript functions that run on PubNub's global network in response to events in your app's message flow. Every Function is bound to a trigger type, and the trigger type governs one behavior: whether the Function intercepts an event synchronously, before delivery, or runs asynchronously on a copy of the event after delivery has already occurred.

Every PubNub plan includes Functions. You write the JavaScript in the Admin Portal. PubNub deploys and runs it on the network. Nothing changes in your client SDK.

The nine trigger types fall into three categories:

| Trigger | Execution | Use for |
| --- | --- | --- |
| Before Publish | Synchronous | Transform, validate, block, or reroute a message before it reaches subscribers |
| Before Publish File | Synchronous | Inspect or reroute a file message before delivery |
| Before Signal | Synchronous | Modify or block a signal before delivery |
| After Publish | Asynchronous | Log, forward, or aggregate a message after delivery |
| After Publish File | Asynchronous | Log or audit file messages after delivery |
| After Signal | Asynchronous | Log or store signal data after delivery |
| After [Presence](https://www.pubnub.com/docs/presence/overview.md) | Asynchronous | React to join, leave, timeout, or state-change events |
| On Interval | Asynchronous | Run code on a repeating schedule |
| On Request | Synchronous | Expose a REST endpoint or call from another Function |

## Synchronous and asynchronous execution

Choosing between synchronous and asynchronous execution is the most significant design decision when picking a trigger type.

**Synchronous Functions** run on the original event. The publisher waits for the Function to complete before PubNub delivers the message or sends the response. This lets you inspect and modify the payload, block delivery entirely, or reroute the message to a different channel. Every operation the Function performs extends the time the publisher waits, including outbound HTTP calls.

Before Publish Functions are fail-closed. If the Functions service is unavailable due to an infrastructure error, PubNub rejects the publish and the publisher receives a 5xx error. This ensures that security-critical or data-critical before-publish logic is never silently bypassed.

**Asynchronous Functions** run on a copy of the event after delivery. They add no latency to the publishing client and cannot change what subscribers received.

You can attach both types to the same channel. A common pattern is to validate and transform a message synchronously (Before Publish), then forward it to an external analytics service asynchronously (After Publish). Subscribers receive the final message without waiting for the analytics call.

## Before-delivery triggers

### Before Publish

A Before Publish Function (full name: Before Publish or Fire) runs on a published message before PubNub delivers it to subscribers. The trigger fires for both `publish()` and `fire()` calls on the channel. Your code can read and modify `request.message`, use the PubNub module to reroute the message to a different channel, or call `request.abort()` to block delivery entirely.

Typical uses:

* Translate message content between languages
* Censor or redact sensitive data
* Normalize missing or invalid fields
* Reroute messages to a moderation channel based on content

### Before Publish File

A Before Publish File Function runs before PubNub delivers a file message. It has the same capabilities as Before Publish.

Typical uses:

* Evaluate file contents via a third-party service
* Block or reroute files flagged as inappropriate
* Check for copyright issues before delivery

### Before Signal

A Before Signal Function runs before PubNub delivers a [signal](https://www.pubnub.com/docs/architecture/core-concepts.md#message). Signals are smaller, transient events not stored by [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md). The Function can modify or block the signal before delivery.

Typical uses:

* Apply custom routing logic based on signal content
* Enrich signals with geographic or contextual data before delivery

## After-delivery triggers

### After Publish

An After Publish Function (full name: After Publish or Fire) runs on a copy of a message after PubNub delivers it. The trigger fires for both `publish()` and `fire()` calls. The Function cannot change what subscribers received.

Typical uses:

* Send messages to external logging services
* Trigger notifications based on keywords or mentions
* Forward messages to secondary channels

### After Publish File

An After Publish File Function runs on a copy of a file message after delivery.

Typical uses:

* Log or audit file activity
* Gather metrics from file uploads

### After Signal

An After Signal Function runs on a copy of a signal after delivery.

Typical uses:

* Log typing state or location data to a user profile
* Integrate signal data with external logging services

### After Presence

An After Presence Function runs after a presence event on a channel. Presence events occur when subscribers connect, disconnect, or time out. The Function reacts to events that have already occurred. It cannot modify presence behavior.

The presence events available to an After Presence Function are:

| Event | When it fires |
| --- | --- |
| `join` | A subscriber joins the channel |
| `leave` | A subscriber leaves the channel |
| `timeout` | A connection drops and the subscriber is not seen for the timeout period (PubNub SDKs set `presenceTimeout` to 300 seconds by default, which is how long PubNub waits without a heartbeat before marking a client offline, configurable via heartbeat settings) |
| `state-change` | A subscriber updates channel state using the state API |
| `interval` | An occupancy count sent at the Presence interval. The keyset's Presence `Interval` setting, the cadence of `interval` events on a channel in interval mode, ranges from 10 to 3,600 seconds. |

Typical uses:

* Send a notification when a priority contact comes online
* Update a key-value (KV) store entry as users join or leave a channel

## Scheduled and on-demand triggers

### On Interval

An On Interval Function runs at a repeating interval that you configure in milliseconds. It does not respond to a message event. The `event` object provides timing data, including the current and last execution timestamps.

Typical uses:

* Refresh a KV store cache from Message Persistence on a schedule
* Package and forward accumulated data to an external service at intervals
* Update user metadata based on recent activity

A related type, Subscribe on Interval, combines subscribe traffic and interval behavior. It is not available to all users. Contact [PubNub support](mailto:support@pubnub.com) to request access.

### On Request

An On Request Function exposes a publicly accessible HTTP endpoint on PubNub's network. You configure the path when you create the Function. Each incoming request arrives as a `request` object with `body`, `headers`, `method`, and `params` fields. The Function calls `response.send()` to return a response.

Typical uses:

* Accept webhooks from third-party services
* Expose an HTTP endpoint for an external service

## Targeting channels

Each Function targets one or more channels. You set the channel pattern when you create the Function:

* **Specific channel name**: the Function runs on events from that exact channel.
* **Wildcard pattern**: the Function runs on events from all matching channels.

Wildcard patterns follow the same dot-delimited hierarchy as [PubNub channel names](https://www.pubnub.com/docs/architecture/core-concepts.md#channel). Functions support up to two wildcard levels:

* `chat.*` matches `chat.general`, `chat.team1`, and any channel with exactly one segment after `chat.`
* `chat.team1.*` matches `chat.team1.general`, `chat.team1.private`, and any channel with one segment after `chat.team1.`

The wildcard must be the last segment. A wildcard in the middle of a pattern is not supported.

Wildcard subscribe requires the Stream Controller add-on with the Wildcard Subscribe option enabled on the keyset. Wildcard channel targeting in a Function depends on the same option.

## Built-in modules

Functions include pre-installed JavaScript modules that you load with `require()`. The runtime does not support native Node.js modules, npm packages, the `process` global, or WebSocket connections. For supported modules and their method contracts, see [Modules and libraries](https://www.pubnub.com/docs/serverless-sdk/modules-and-libraries/overview.md).

### Key-value store

The KV store is a persistent, globally distributed key-value database scoped to your subscribe key. All Functions on the same keyset read from and write to the same store. The store is eventually consistent across PubNub's global network.

Storage constraints:

* A KV store key can be up to 1,000 characters.
* A KV store value can be up to 32,000 characters.
* A KV store entry lives for 1 day by default, and a per-entry TTL can range from 1 minute up to 1 year.

The KV store supports atomic counter increments via `incrcounter()`. The operation increments a value server-side, so concurrent Function executions do not overwrite each other's updates. This makes it accurate for vote counts, event tallies, and similar metrics that multiple clients update at the same time.

### Outbound HTTP

The `xhr` (XMLHttpRequest) module lets a Function make outbound HTTP and HTTPS requests to external services. Use it to call external APIs, deliver data to webhooks, or fetch data to enrich a message payload.

Outbound HTTP calls add latency. In synchronous Functions, each request extends the time the publisher waits. Keep network calls out of synchronous Functions unless the response is needed to decide whether to block or transform the message.

## Limits

Functions have plan-specific performance limits and per-execution operation caps. For the current numeric limits and their scope, see [API limits](https://www.pubnub.com/docs/serverless-sdk/api-limits.md).

Last updated at: 2026-09-30T07:20:08.000Z
