On this page

XHR Module

The xhr module lets you make HTTP or HTTPS requests from a PubNub Function to external APIs and services. Use it to call webhooks, integrate third-party endpoints, and enrich messages in real time.

Import it with require():

1const xhr = require("xhr");

Fetch

fetch() is the only method of xhr.

Arguments

  • url
    • type: string
    • required: true
    • description: Target URL.
  • http_options
    • type: object
    • required: false
    • description: Request options. See http_options for attributes.

Examples

Simple GET request

1export default (event) => {
2 xhr.fetch('https://neutrinoapi.com/geocode-address').then((serverResponse) => {
3 // handle server response
4 }).catch((err) => {
5 // handle non-success response
6 });
7}

Post request

1export default (event) => {
2 const xhr = require('xhr');
3 const http_options = {
4 'method': 'POST', // or PUT
5 'body': 'foo=bar&baz=faz'
6 };
7
8 const url = 'http://httpbin.org/post';
9
10 return xhr.fetch(url, http_options)
11 .then((resp) => {
12 const body = JSON.parse(resp.body);
13 console.log(body);
14 return event.ok('Request succeeded');
15 })
show all 19 lines

Post request with JSON request payload

1export default (event) => {
2 const xhr = require('xhr');
3 const http_options = {
4 'method': 'POST',
5 'headers': {
6 'Content-Type': 'application/json'
7 },
8 'body': JSON.stringify({
9 'body': 'Posting JSON!',
10 'to': 'Someone Special!'
11 })
12 };
13
14 const url = 'http://httpbin.org/post';
15
show all 25 lines

Post request with form encoded payload

1export default (event) => {
2 const xhr = require('xhr');
3 const http_options = {
4 'method': 'POST',
5 'headers': {
6 'Content-Type': 'application/x-www-form-urlencoded',
7 },
8 'body': 'foo=bar&z=x&abc=123'
9 };
10
11 const url = 'http://httpbin.org/post';
12
13 return xhr.fetch(url, http_options)
14 .then((resp) => {
15 const body = JSON.parse(resp.body);
show all 22 lines

Http_options

NameTyperequiredDefaultDescription
method
string
false
GET
Request method. Supported: GET, POST, PUT, OPTIONS, DELETE, PATCH.
body
string
true for POST and PUT
Request payload. For JSON, set both headers and body.
encoding
string
false
utf8
Encoding used to decode the response body to string.
headers
object
false
Request headers.
timeout
integer
false
5,000
Timeout in milliseconds. Max 10,000 (10 seconds).
retries
integer
false
3
Retry count within the Function’s 10‑second window. Uses the smaller of your input and the default (3). Retries on ECONNRESET, ECONNREFUSED, and EMFILE.

Returned Object

fetch() returns a response promise. Handle rejected promises:

1    export default (request) => {
2 const xhr = require('xhr');
3 return xhr.fetch(
4 'https://httpbin.org/status/200',
5 {
6 headers: {
7 'Content-Type': 'application/json'
8 }
9 }
10 )
11 .then((res) => {
12 console.log(res);
13 return request.ok('Request succeeded.')
14 })
15 .catch((err) => {
show all 18 lines

Response Object

NameTypeDescription
body
string
Decoded response body based on default or user-specified encoding
buffer
object
Response body buffer
headers
object
Response headers
url
string
Request URL
status
integer
Status code
statusText
string
Status text
ok
bool
True if status code is 2XX
bodyUsed
bool
Whether the body has been read.

Runtime limits

Within one Function execution, you can perform up to three combined operations across KV store, XHR, and publish.

Tips

  • Prefer triggerRequestFunction from the PubNub Module for invoking On Request Functions.
  • If many XHR requests fail over time, monitor and restart Functions as needed.
Last updated on