Connecting with Node.js
This guide explains how to establish a connection between a Node.js application and a Redis database using the redis package. It walks through the necessary setup, configuration, and execution of a simple Redis command.
Variables
To successfully connect to a Redis instance, you’ll need to provide the following parameters. These can typically be found on the Elestio service overview page.
Variable |
Description |
Purpose |
---|---|---|
|
Redis hostname (from Elestio service overview) |
The address of the server hosting your Redis instance. |
|
Redis port (from Elestio service overview) |
The port used for the Redis connection. The default Redis port is 6379. |
|
Redis password (from Elestio service overview) |
Authentication key used to connect securely to the Redis instance. |
Make sure to copy these values from the Elestio Redis service details and plug them into your code.
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 Redis.
npm install redis --save
Code
Create a new file named redis.js
and add the following code:
const redis = require("redis");
// Redis connection configuration
const config = {
socket: {
host: "HOST",
port: PORT,
},
password: "PASSWORD",
};
// Create a Redis client
const client = redis.createClient(config);
// Handle connection errors
client.on("error", (err) => {
console.error("Redis connection error:", err);
});
// Connect and run a test command
(async () => {
try {
await client.connect();
console.log("Connected to Redis");
// Set and retrieve a test key
await client.set("testKey", "Hello Redis");
const value = await client.get("testKey");
console.log("Retrieved value:", value);
// Disconnect from Redis
await client.disconnect();
} catch (err) {
console.error("Redis operation failed:", err);
}
})();
To execute the script, open the terminal or command prompt and navigate to the directory where redis.js
is located. Once in the correct directory, run the script with the command:
node redis.js
If the connection is successful, the output should resemble:
Connected to Redis
Retrieved value: Hello Redis