Question: How to Connect to Redis ElastiCache from Node.js

Answer

To connect to a Redis ElastiCache cluster from a Node.js application, follow these steps:

  1. Install the redis package using npm:

    npm install redis
    
  2. Import the redis package in your Node.js file and create a Redis client instance with the appropriate configuration options:

    const redis = require('redis'); // Replace the following values with your ElastiCache configuration details const host = 'your-elasticache-endpoint-url'; const port = 6379; // Default Redis port // Create the Redis client const client = redis.createClient({ host, port });
  3. Configure error and connection event handlers for the Redis client:

    // Handle errors client.on('error', (error) => { console.error(`Redis error: ${error}`); }); // Connection event client.on('connect', () => { console.info('Connected to ElastiCache Redis'); });
  4. Use the Redis client to interact with your ElastiCache instance using available Redis commands:

    // Set a key-value pair in the cache client.set('my_key', 'my_value', (err, response) => { if (err) { console.error(`Set error: ${err}`); } else { console.log(`Set response: ${response}`); } }); // Retrieve the value of the key from the cache client.get('my_key', (err, value) => { if (err) { console.error(`Get error: ${err}`); } else { console.log(`Get value: ${value}`); } });
  5. Remember to close the connection when you're done using it:

    client.quit();

Here's a full example:

const redis = require('redis'); const host = 'your-elasticache-endpoint-url'; const port = 6379; const client = redis.createClient({ host, port }); client.on('error', (error) => { console.error(`Redis error: ${error}`); }); client.on('connect', () => { console.info('Connected to ElastiCache Redis'); }); client.set('my_key', 'my_value', (err, response) => { if (err) { console.error(`Set error: ${err}`); } else { console.log(`Set response: ${response}`); } }); client.get('my_key', (err, value) => { if (err) { console.error(`Get error: ${err}`); } else { console.log(`Get value: ${value}`); } }); // Close the connection when you're done client.quit();

Make sure to replace your-elasticache-endpoint-url with your actual ElastiCache cluster endpoint URL and customize the code as needed.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book
Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.