---
source_url: https://www.pubnub.com/docs/serverless/functions/functions-apis/xhr-module
title: XHR Module
updated_at: 2026-06-11T11:38:15.861Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# 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()`:

```javascript
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:

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

POST request:

```javascript
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');
        })
        .catch((err) => {
            return event.ok(`Request Failed: ${err}`);
        });
};
```

POST request with JSON payload:

```javascript
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';

    return xhr.fetch(url, http_options)
        .then((resp) => {
            const body = JSON.parse(resp.body);
            console.log(body);
            return event.ok('Request succeeded');
        })
        .catch((err) => {
            return event.ok(`Request Failed: ${err}`);
        });          
};
```

POST request with form-encoded payload:

```javascript
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);
            console.log(body);
        return event.ok('Request succeeded');
        })
        .catch((err) => {
            return event.ok(`Request Failed: ${err}`);
        });  
};
```

### Http_options

| Name | Type | required | Default | Description |
| --- | --- | --- | --- | --- |
| `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:

```javascript
    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) => {
            return request.abort(`Request failed: ${err}`);
        })
    };
```

### Response Object

| Name | Type | Description |
| --- | --- | --- |
| `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.

:::note Functions support
If you need help with a scenario not covered here, contact [PubNub Support](https://www.pubnub.com/docs/mailto:support@pubnub.com).
:::