XHR Module

The xhr module lets you make HTTP or HTTPS requests from a PubNub Function. Use it to call APIs, trigger webhooks, and enrich messages in real time.

Import it with require():

const xhr = require("xhr");

Exposed methods

The module exposes one method: fetch().

Arguments

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

Examples

Examples:

Simple GET request:

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

POST request:

export default (event) => {
const xhr = require('xhr');
const http_options = {
'method': 'POST', // or PUT
'body': 'foo=bar&baz=faz'
};

const url = 'http://httpbin.org/post';

return xhr.fetch(url, http_options)
.then((resp) => {
const body = JSON.parse(resp.body);
console.log(body);
return event.ok('Request succeeded');
})
show all 19 lines

POST request with JSON payload:

export default (event) => {
const xhr = require('xhr');
const http_options = {
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'body': JSON.stringify({
'body': 'Posting JSON!',
'to': 'Someone Special!'
})
};

const url = 'http://httpbin.org/post';

show all 25 lines

POST request with form-encoded payload:

export default (event) => {
const xhr = require('xhr');
const http_options = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded',
},
'body': 'foo=bar&z=x&abc=123'
};

const url = 'http://httpbin.org/post';

return xhr.fetch(url, http_options)
.then((resp) => {
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 in http_options.
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. Maximum is 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:

    export default (request) => {
const xhr = require('xhr');
return xhr.fetch(
'https://httpbin.org/status/200',
{
headers: {
'Content-Type': 'application/json'
}
}
)
.then((res) => {
console.log(res);
return request.ok('Request succeeded.')
})
.catch((err) => {
show all 18 lines

Response Object

NameTypeDescription
body
string
Decoded response body based on the 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

In one Function run, you can do up to three total operations across KV store, XHR, and publish.

Tips

  • Use triggerRequestFunction from the PubNub Module to invoke On Request Functions.
  • If many XHR requests fail over time, monitor and restart Functions as needed.
Functions support

If you need help with a scenario not covered here, contact PubNub Support.

Last updated on