Skip to main content

Connecting with Node.js

This guide explains how to establish a connection between a Node.js application and a Valkey database using the redis package. It walks through the necessary setup, configuration, and execution of a simple Valkey command.

Variables

To successfully connect to a Valkey instance, you’ll need to provide the following parameters. These can typically be found on the Elestio service overview page.

Variable

Description

Purpose

HOST

Valkey hostname (from Elestio service overview)

The address of the server hosting your Valkey instance.

PORT

Valkey port (from Elestio service overview)

The port used for the Valkey connection. The default Valkey port is 6379.

PASSWORD

Valkey password (from Elestio service overview)

Authentication key used to connect securely to the Valkey instance.

These values can usually be found in the Elestio service overview details as shown in the image below, make sure to take a copy of these details and add it to the code moving ahead.

Screenshot 2025-07-04 at 4.12.37 PM.jpg

Prerequisites

Install Node.js and NPM

  • Check if Node.js is installed by running:

node -v
  • If not installed, download and install it from nodejs.org.

  • Confirm npm is installed by running:

npm -v

Install the redis Package

The redis package enables communication between Node.js applications and Valkey.

npm install redis --save

Code

Create a new file named valkey.js and add the following code:

const valkey = require("redis");

// Valkey connection configuration
const config = {
  socket: {
    host: "HOST",
    port: PORT,
  },
  password: "PASSWORD",
};

// Create a Redis client
const client = valkey.createClient(config);

// Handle connection errors
client.on("error", (err) => {
  console.error("Valkey connection error:", err);
});

// Connect and run a test command
(async () => {
  try {
    await client.connect();
    console.log("Connected to Valkey");

    // Set and retrieve a test key
    await client.set("testKey", "Hello Valkey");
    const value = await client.get("testKey");
    console.log("Retrieved value:", value);

    // Disconnect from Valkey
    await client.disconnect();
  } catch (err) {
    console.error("Valkey operation failed:", err);
  }
})();

To execute the script, open the terminal or command prompt and navigate to the directory where valkey.js is located. Once in the correct directory, run the script with the command:

node valkey.js

If the connection is successful, the output should resemble:

Connected to Valkey  
Retrieved value: Hello Valkey