# How to Connect to Redis and Execute Commands Using DBX

> Learn to connect to Redis and run commands with DBX. This guide covers native ioredis clients and HTTP bridge for Sentinel, simplifying your Redis interactions.

- Repository: [skyler/dbx](https://github.com/t8y2/dbx)
- Tags: how-to-guide
- Published: 2026-07-08

---

**DBX provides a unified API to connect to Redis and execute commands either through a native `ioredis` client for standalone instances or via an HTTP bridge for complex setups like Sentinel, automatically handling safety classification and result conversion.**

The `t8y2/dbx` repository treats Redis as a first-class data source, exposing a high-level TypeScript API that abstracts connection complexity while maintaining security controls. Whether you are running simple GET/SET operations against a local instance or managing production clusters through SSH tunnels, DBX handles the transport layer, command validation, and response normalization automatically.

## Understanding DBX Redis Connection Architecture

DBX determines how to execute Redis commands based on your connection configuration. The internal `hasDirectRedisSupport` function in [`packages/node-core/src/database.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/database.ts) evaluates whether DBX can open a native client or must route through the bridge process.

### Direct Execution Mode

For standalone Redis endpoints without SSH tunneling or proxy layers, DBX instantiates a native `ioredis` client locally. This path provides the lowest latency and is used when `executeRedisCommand` detects a simple host/port configuration with `db_type: "redis"`.

### Bridge Execution Mode

When connecting to Redis Sentinel, Cluster configurations, or instances behind SSH tunnels, DBX forwards commands to the DBX bridge process via an HTTP POST to `/data/redis/execute-command`. The bridge then executes the command on the remote instance and returns the serialized result. This logic resides in [`packages/node-core/src/database.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/database.ts) (lines 389-395).

## Safety-First Command Execution

Before executing any command, DBX validates it against a safety classification system defined in [`packages/node-core/src/redis-command.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/redis-command.ts). Commands are categorized into three levels:

- **Allowed** – Safe read operations executed immediately
- **Confirm** – Write operations that may require explicit confirmation
- **Blocked** – Dangerous commands like `FLUSHALL` or `KEYS` that raise errors by default

You can inspect a command's classification using `classifyRedisCommand` or override restrictions with the `skipSafetyCheck` option, though this is discouraged for production environments.

## Executing Redis Commands

### Standalone Redis Connection

For direct connections to standalone Redis instances, construct a `ConnectionConfig` object with `db_type: "redis"` and call `executeRedisCommand`:

```typescript
import { executeRedisCommand } from "dbx";

const redisConn = {
  id: "redis-local",
  name: "local-redis",
  db_type: "redis",
  host: "127.0.0.1",
  port: 6379,
  username: "default",
  password: "s3cr3t",
};

async function demoDirectConnection() {
  // Read operations (allowed)
  const getResult = await executeRedisCommand(redisConn, 0, "GET myKey");
  console.log("Value:", getResult.value);

  // Write operations (confirm level)
  const setResult = await executeRedisCommand(redisConn, 0, "SET myKey \"Hello DBX\"");
  console.log("Status:", setResult.value); // "OK"
}

demoDirectConnection();

```

The second parameter (`0`) specifies the Redis database index (0-15).

### Sentinel and Cluster Configurations

For Redis Sentinel or Cluster setups, specify the connection mode and master name. DBX automatically routes these through the bridge process:

```typescript
import { executeRedisCommand } from "dbx";

const sentinelConn = {
  id: "redis-sentinel",
  name: "sentinel-cluster",
  db_type: "redis",
  host: "sentinel.example.com",
  port: 26379,
  redis_connection_mode: "sentinel",
  redis_sentinel_master: "mymaster",
  redis_sentinel_password: "s3cr3t",
};

async function querySentinel() {
  // Automatically uses bridge mode
  const result = await executeRedisCommand(sentinelConn, 2, "GET session:42");
  console.log("Session data:", result.value);
}

querySentinel();

```

### Bypassing Safety Checks for Dangerous Commands

Blocked commands like `KEYS` or `FLUSHALL` throw errors unless you explicitly override safety checks. Use `evaluateRedisCommandSafety` to check classification before bypassing:

```typescript
import { executeRedisCommand, classifyRedisCommand, evaluateRedisCommandSafety } from "dbx";

const dangerousCmd = "KEYS *";

// Check classification first
console.log("Safety level:", classifyRedisCommand(dangerousCmd)); // "blocked"

// Evaluate with override intent
const decision = evaluateRedisCommandSafety(dangerousCmd, { allowDangerous: true });

if (decision.allowed) {
  // Execute with explicit safety bypass
  const keys = await executeRedisCommand(redisConn, 0, dangerousCmd, {
    skipSafetyCheck: true,
  });
  console.log("All keys:", keys.value);
}

```

The `options` object supports `skipSafetyCheck` (boolean) and `timeoutMs` (number) for customizing request behavior.

## Handling Command Results

Raw values returned by `ioredis` (including Buffers, nested arrays, and Redis objects) are recursively transformed into plain JSON via `redisValueToJson` and `redisTextToJson` functions in [`packages/node-core/src/database.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/database.ts) (lines 1007-1026). This ensures that `executeRedisCommand` always returns a clean `RedisCommandResult` with serializable values, regardless of whether the execution was direct or bridge-based.

## Summary

- **DBX supports two execution paths**: Native `ioredis` for standalone connections and HTTP bridge for Sentinel, Cluster, or tunneled setups.
- **Safety controls are mandatory**: Commands are classified as allowed, confirm, or blocked in [`packages/node-core/src/redis-command.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/redis-command.ts), with `skipSafetyCheck` available for emergency overrides.
- **Configuration-driven**: Set `db_type: "redis"` and appropriate connection modes (`redis_connection_mode`) to trigger the correct execution path.
- **Automatic serialization**: Raw Redis responses are converted to JSON via `redisValueToJson` before reaching your application code.

## Frequently Asked Questions

### Does DBX support Redis Cluster?

Yes, DBX supports Redis Cluster through the bridge execution mode. When your `ConnectionConfig` includes cluster-specific parameters or SSH tunneling, `hasDirectRedisSupport` returns false, causing `executeRedisCommand` to route the request through the DBX bridge process at `/data/redis/execute-command`. The bridge handles the cluster topology and node selection transparently.

### How does DBX handle authentication for Redis connections?

DBX passes authentication credentials (username, password, sentinel passwords) directly to the underlying `ioredis` client or includes them in the bridge payload. For Sentinel configurations, use `redis_sentinel_password` and `redis_sentinel_master` in your connection object. Standard Redis AUTH is handled via the `username` and `password` fields in the `ConnectionConfig`.

### Can I run Redis Lua scripts through DBX?

Yes, you can execute Lua scripts using the `EVAL` or `EVALSHA` commands through `executeRedisCommand`. These commands are typically classified at the "confirm" safety level. Pass the script and keys as you would in standard Redis CLI format: `EVAL "return redis.call('GET', KEYS[1])" 1 myKey`. The script results undergo the same JSON conversion as standard command responses.

### What happens if a Redis command is blocked by safety checks?

By default, blocked commands (like `FLUSHALL`, `KEYS`, or `CONFIG SET`) throw a safety error before execution. The error message indicates the command is restricted. To execute blocked commands deliberately, first call `evaluateRedisCommandSafety` to verify the classification, then pass `skipSafetyCheck: true` in the options parameter of `executeRedisCommand`. Use this override cautiously, as it bypasses protections against dangerous operations in production environments.