---
source_url: https://www.pubnub.com/docs/sdks/ruby/api-reference/configuration
title: Configuration API for Ruby SDK
updated_at: 2026-06-04T11:13:00.565Z
sdk_name: PubNub Ruby SDK
sdk_version: 6.0.2
---

> 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


# Configuration API for Ruby SDK

PubNub Ruby SDK, use the latest version: 6.0.2

Install:

```bash
gem install pubnub@6.0.2
```

Complete API reference for building real-time applications on PubNub with the Ruby Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.

## Initialization

### Installing

To use `pubnub` ruby gem, you need to install it. You can do it via `rubygems` command:

```ruby
gem install pubnub
```

Or add it to your Gemfile.

```ruby
gem 'pubnub', '~> 6.0.2'
```

### Usage

To use `pubnub`, require it in your files.

```ruby
require 'pubnub'
```

### Description

This function initializes the PubNub Client API context. Call it before using any APIs to establish account-level credentials such as `publish_key` and `subscribe_key`.

### Method(s)

To `Initialize` PubNub you can use the following method(s) in the Ruby SDK:

```ruby
Pubnub(
    subscribe_key,
    publish_key,
    secret_key,
    auth_key,
    ssl,
    user_id,
    heartbeat,
    callback,
    ttl,
    open_timeout,
    read_timeout,
    idle_timeout,
    s_open_timeout,
    s_read_timeout,
    s_idle_timeout,
    logger,
    origin,
    http_sync,
    crypto_module
)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscribe_key | String, | Yes |  | Your `subscribe key`. |
| publish_key | String, | Optional |  | Your `publish key`, required to publish messages. |
| secret_key | String, | Optional |  | Your `secret key`, required for Access Manager. |
| auth_key | String, | Optional |  | Your `auth key`. |
| ssl | Boolean | Optional | `false` | If set to `true`, `ssl` connection will be used. |
| user_id | String | Yes |  | [User ID](https://www.pubnub.com/docs/general/basics/identify-users-and-devices) to use. You should set a unique user ID to identify the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the user ID, you won't be able to connect to PubNub. |
| heartbeat | Integer | Optional |  | That single value serves a two-fold purpose. First of all, it specifies how often the client will send heartbeat signals to the server to confirm its activity on a channel. Secondly, the value defines a timeout period after which the server considers the client inactive, with inactivity beyond this period triggering a "timeout" on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). Disabled by default. |
| callback | Lambda | Optional |  | That `callback` will be automatically passed to all method calls fired from this client (like `publish`, `history`, `subscribe`). Will be overwritten by the `callback` passed to called event. |
| ttl | Integer | Optional |  | Default `ttl` for grant and revoke. |
| open_timeout | Integer | Optional | `10` | Timeout for opening connection for `non-subscribe` events. The value is in seconds. |
| read_timeout | Integer | Optional | `10` | Timeout for reading for `non-subscribe` events. The value is in seconds. |
| idle_timeout | Integer | Optional | `10` | Timeout for idle for `non-subscribe` events. The value is in seconds. |
| s_open_timeout | Integer | Optional | `310` | Timeout for opening connection for `subscribe`. The value is in seconds. |
| s_read_timeout | Integer | Optional | `310` | Timeout for read for `subscribe`. The value is in seconds. |
| s_idle_timeout | Integer | Optional | `310` | Timeout for idle for `subscribe`. The value is in seconds. |
| logger | Object | Optional | `Logger instance that outputs logs to 'pubnub.log'` | Custom `logger` instance. For detailed information about logging options and customization, refer to the [Logging](https://www.pubnub.com/docs/sdks/ruby/logging) document. |
| origin | String | Optional | `ps.pndsn.com` | Custom `origin`. Add method that allows changing the `origin`.`#origin=(origin)` To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| http_sync | Boolean | Optional | `false` | Method will be executed `asynchronously` and will return future, to get it's `value` you can use `value` method. If set to `true`, method will return array of envelopes (even if there's only one `envelope`). For `sync` methods `Envelope` object will be returned. |
| crypto_module | Crypto::CryptoModule | Optional |  | The cryptography module used for encryption and decryption of messages. Takes the `cipher_key` and `random_iv` parameters as arguments. For detailed encryption configuration and examples, refer to the [Encryption API](https://www.pubnub.com/docs/sdks/ruby/api-reference/encryption) page. |
| cipher_key | String | Optional |  | This way of setting this parameter is deprecated, pass it to `crypto_module` instead. Your cipher key, it's used to encrypt and decrypt messages, if set. |
| random_iv | Boolean | Optional | `true` | This way of setting this parameter is deprecated, pass it to `crypto_module` instead. When true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload. |
| uuid | String | Yes |  | This parameter is deprecated, use `user_id` instead. UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub. If you don't set the UUID, you won't be able to connect to PubNub. |

:::warning Disabling random initialization vector
Disable random initialization vector (IV) only for backward compatibility (< `4.6.0`) with existing applications. Never disable random IV on new applications.
:::

#### crypto_module

`crypto_module` encrypts and decrypts messages and files. From 5.2.2, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption).

For configuration details, implementation examples, and manual encryption methods, see [Encryption](https://www.pubnub.com/docs/sdks/ruby/api-reference/encryption).

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in the PubNub config.
:::

### Sample code

#### Initialize the PubNub client API with encryption

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```ruby
require 'pubnub'

def main
  # Configuration for PubNub instance
  pubnub = Pubnub.new(
    subscribe_key: ENV.fetch('SUBSCRIBE_KEY', 'demo'),
    publish_key: ENV.fetch('PUBLISH_KEY', 'demo'),
    ssl: true,
    user_id: 'myUniqueUserId',
    crypto_module: Pubnub::Crypto::CryptoModule.new_aes_cbc("enigma", true)
  )

  # Example to demonstrate successful configuration
  puts "PubNub client initialized successfully with user_id: #{pubnub.user_id}"
end

if __FILE__ == $0
  main
  puts 'finished'
end
```

### Returns

It returns the PubNub instance for invoking PubNub APIs like `publish()`, `subscribe()`, `history()`, `here_now()`, etc.

### Other examples

#### Initialize the client

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```ruby
pubnub = Pubnub.new(
    publish_key: 'demo',
    subscribe_key: 'demo',
    user_id: 'myUniqueUserId'
)
```

#### Initialization for a read-only client

In the case where a client will only read messages and never publish to a channel, you can simply omit the `publish_key` when initializing the client:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```ruby
# Initialize for read-only client
# Note: The following line uses a hash argument. Ensure the key and value
# are separated by a colon and a space (Ruby keyword argument style):
# subscribe_key: 'demo'
pubnub = Pubnub.new(
    subscribe_key : 'demo'
)
```

#### Use a custom user ID

Set a custom `user_id` to identify your users.

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```ruby
# initialize
pubnub = Pubnub.new(
    publish_key: 'myPublishKey',
    subscribe_key: 'mySubscribeKey',
    user_id: 'myUniqueUserId'
)
```

#### Initializing with SSL enabled

This examples demonstrates how to enable PubNub Transport Layer Encryption with `SSL`. Just initialize the client with `ssl` set to `true`. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```ruby
pubnub = Pubnub.new(
    subscribe_key: :demo,
    publish_key:   :demo,
    ssl: true,
    user_id: 'myUniqueUserId'
)
```

#### Initializing with Access Manager

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note Secure your secret_key
Anyone with the `secret_key` can grant and revoke permissions to your app. Never let your secret key be discovered, and to only exchange it / deliver it securely. Only use the `secret_key` on secure server-side platforms.
When you init with `secret_key`, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
:::

For applications that will administer Access Manager permissions, the API is initialized with the `secret_key` as in the following example:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```ruby
pubnub = Pubnub.new(subscribe_key: 'my_subkey', secret_key: 'my_secretkey', user_id: 'myUniqueUserId')
```

Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the `secret_key` to sign all Access Manager messages to the PubNub Network.

## Event listeners

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

#### Add listeners

```ruby
callback = Pubnub::SubscribeCallback.new(
    message:  ->(_envelope) {}, # this will be fired only for non-presence messages
    presence: ->(_envelope) {}, # this will be fired only for presence messages
    signal: ->(_envelope) {}, # Handle signal message
    status: ->(envelope)  do  # this will be fired for status messages and errors
    if envelope.status[:error]
        case envelope.status[:category]
            when Pubnub::Constants::STATUS_ACCESS_DENIED # :access_denied
                # Access denied. Double check Access Manager etc.
            when Pubnub::Constants::STATUS_TIMEOUT # :timeout
                # Timeout error
            when Pubnub::Constants::STATUS_NON_JSON_RESPONSE # :non_json_response
                # Non json response
            when Pubnub::Constants::STATUS_API_KEY_ERROR # :api_key_error
                # API key error
            when Pubnub::Constants::STATUS_ERROR
                # Other error
            else
                # Shouldn't happen
            end
        end
    end
)

pubnub.add_listener(name: 'my_listener', callback: callback)
```

#### Remove listeners

```ruby
pubnub.remove_listener(name: 'my_listener')
# or
pubnub.remove_listener(callbacks)
```

#### Listeners example

```ruby
# Init pubnub client
pubnub_client = Pubnub.new(subscribe_key: 'demo', publish_key: 'demo')

# First callbacks object
callbacks0 = Pubnub::SubscribeCallback.new(
  message:  ->(envelope) { puts "C0 MESSAGE: #{envelope.result[:data][:message]}" },
  presence: ->(envelope) { puts "C0 PRESENCE: #{envelope.result[:data][:message]}" },
  status:   ->(envelope) { puts "C0 STATUS: #{envelope.result[:data][:message]}" }
)

# Second callbacks object
callbacks1 = Pubnub::SubscribeCallback.new(
  message:  ->(envelope) { puts "C1 MESSAGE: #{envelope.result[:data][:message]}" },
  presence: ->(envelope) { puts "C1 PRESENCE: #{envelope.result[:data][:message]}" },
  status:   ->(envelope) { puts "C1 STATUS: #{envelope.result[:data][:message]}" }
)

# Add listener allows you to specify name, it's not required to specify a name
pubnub_client.add_listener(name: 'c0', callback: callbacks0)

# Let's subscribe somewhere
pubnub_client.subscribe(channel: :demo, presence: :demo)

# SOME OUTPUT:
# C0 PRESENCE: {"action"=>"join", "timestamp"=>1461683357, "user_id"=>"fc0c0460-44b4-4338-b7e9-1b534b85072e", "occupancy"=>2}
# C0 MESSAGE: {"text"=>"hey"}
# C0 PRESENCE: {"action"=>"join", "timestamp"=>1461683374, "user_id"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>3}
# C0 MESSAGE: {"text"=>"hey"}

# Add another subscriber
pubnub_client.add_listener(name: 'c1', callback: callbacks1)

# SOME OUTPUT WITH TWO LISTENERS ACTIVE:
# C0 MESSAGE: {"text"=>"hey"}
# C1 MESSAGE: {"text"=>"hey"}
# C0 PRESENCE: {"action"=>"leave", "timestamp"=>1461683435, "user_id"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>2}
# C1 PRESENCE: {"action"=>"leave", "timestamp"=>1461683435, "user_id"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>2}

# We're removing subscriber by giving it's name
pubnub_client.remove_listener(name: 'c1')

# SOME OUTPUT AFTER REMOVING C1 LISTENER
# C0 MESSAGE: {"text"=>"hey"}
# C0 MESSAGE: {"text"=>"hey"}
# C0 PRESENCE: {"action"=>"join", "timestamp"=>1461683698, "user_id"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>2}

# We're removing subsciber by giving it's object, now we don't have any listeners active
pubnub_client.remove_listener(callback: callbacks0)
```

## Presence to a channel group

This functions subscribes to the presence channel of a channel group.

### Method(s)

To do `Presence to a Channel Group` you can use the following method(s) in Ruby SDK:

* [Go to the subscribe() method](https://www.pubnub.com/docs/sdks/ruby/api-reference/publish-and-subscribe#subscribe).

### Sample code

Subscribe to the presence channel of a channel group

```ruby
pubnub = Pubnub.new(
    subscribe_key: :demo,
    publish_key: :demo
)

callback = Pubnub::SubscribeCallback.new(
    message:  ->(_envelope) {
    },
    presence: ->(envelope) {
        puts "PRESENCE: #{envelope.result[:data]}"
    },
    status:   ->(_envelope) {
    }
)

pubnub.add_listener(callback: callback)

pubnub.presence(channel_groups: 'family')
```

## Authentication key

This function provides the capability to get a user's `auth_key`.

### Method(s)

```ruby
auth_key
```

This method doesn't take any arguments.

### Sample code

```ruby
pubnub.auth_key
```

### Returns

The current authentication key.

## Terms in this document

* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.