Having trouble connecting to the online redis database

I am currently working on establishing a connection to my online redis database.

const redis = require('redis');

const client = redis.createClient({
  password: '<password>',
  socket: {
      host: <host>
      port: <port>
  }
});

client.on('connect', function() {
  console.log('client connected');
});

client.on('error', function(err) {
  console.error('Error connecting to server: ', err); 
});

client.set('mykey', 'myvalue', function(err, result) { 
  if (err) {
    console.error('Error setting value - : ', err);
  } else {
    console.log('Value set - ', result);
  }
});

However, while trying to run the code, I encountered an error message stating "Unhandled Runtime Error: Error: The client is closed." Some sources suggest calling the "Connect" method on the client as a solution; however, attempts to do so have resulted in the error messages "client.connect" or "net.connect" is not a function. I would appreciate any advice on resolving this issue.

To establish a connection with my Redis database, I have installed the necessary dependencies using npm package manager: redis, ioredis, redis-om, and node-redis.

In addition, I have replaced the placeholders , , and with the actual values provided by redis.

Answer №1

In the latest version of Node Redis, version 4.x, Promises are now used instead of callbacks for handling asynchronous tasks. If you're looking for an example of how to connect using this new method, you can refer to the connection example in the README file at this link:

import { createClient } from 'redis';

const client = createClient();

client.on('error', err => console.log('Redis Client Error', err));

await client.connect();

await client.set('key', 'value');
const value = await client.get('key');
await client.disconnect();

It's important to note that you only need the redis package for your specific task, as it is the official Node.js client for Redis. Although I have created a package called redis-om which utilizes the redis package, it's not necessary for what you're trying to achieve.

Answer №2

I encountered a similar issue in the past and was able to resolve it by installing the ioredis package. After implementing the following solution, the error was no longer present:

import Redis from "ioredis";

const client = new Redis({
  host: <host>,
  port: <port>,
  password: <password>,
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an issue with cookie handling during the process of authenticating users through supabase/ssr using Google OAuth

I am developing a Next.js project with the integration of Supabase. User authentication is done through Supabase clients using Google OAuth providers. I have followed the exact code from this GitHub repository: https://github.com/SamuelSackey/nextjs-supaba ...

"The requested origin does not have the necessary 'Access-Control-Allow-Origin' header" CORS issue encountered using the npm package CORS

I'm currently working on a project that involves a React app paired with a NodeJS server. My React app is running on port 3000, while my server is running on port 5000. The issue arises when I attempt to make a POST request to "/api/users/login". Th ...

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

Challenges faced with password hashing in Express.js

Can anyone assist me with the process of hashing passwords? I had a functional login/register feature on my express app until I integrated bcrypt. After registering a User, I can see that the password is hashed in the Database. However, when attempting to ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

The latest version of Express, v4.0.0, does not offer the --sessions command or cmd, while previous versions

As someone who isn't very familiar with Express, I'm curious as to why the latest version 4.0.0 doesn't include the --sessions command. When I was using version 3.4.8, this command was available, but after upgrading to the newest version, I ...

Transferring binary fragments to Node.js for assembly into a complete file. Creating a file

Hey there, I'm in a bit of a bind. I'm trying to send file chunks using multiple XMLHttpRequest requests and then receive these parts in Node.js to reconstruct the original file from the binary data. The issue I'm facing is that the final f ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

encountering an issue following the initial setup using create-next-app

After searching on Stack Overflow and finding no answers, I am posting this question again. When I create a new project in Next.js using npx create-next-app project-name --ts and run npm run dev without making any changes to the source code, I encounter t ...

Exploring the combination of MongoDB and NextJS: Easily identify corresponding data regardless of capitalization

This code aims to retrieve and display the latest data on Covid-19 related fatalities, recoveries, and critical cases worldwide. The search function is defined as: const search = (e) => { e.preventDefault() //to prevent page reload cons ...

What is the best way to transform information stored in a buffer to another buffer?

My current task involves writing a unit test to validate the functionality of my signature function, which computes the signature of incoming data from a webhook. The function is performing correctly and accurately calculating the signature. exports.checkS ...

What is the reason behind npm displaying "verb" and "sill" messages during the installation process?

Can someone explain the purpose of using the terms "verb" and "sill" during the process of installing node modules via npm? ⋊> ~/t/quill on develop ◦ npm install ...

Fixing problems encountered when asynchronously gunzipping an already read file in Node.js

As a newcomer to the world of node.js and asynchronous programming, I have successfully used promises to read files with fs readFile, but I am struggling with getting zlib Gunzip to function as expected in my Coffeescript code: promisifyRun(fs, 'r ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

What is the best way to indicate a particular element within a subdocument array has been altered in mongoose?

I have a specific structure in my Mongoose schema, shown as follows: let ChildSchema = new Schema({ name:String }); ChildSchema.pre('save', function(next){ if(this.isNew) /*this part works correctly upon creation*/; if(this.isModifi ...

Changing the NextJS route triggers a re-render of the _app.js file due to the usage of next-i18next serverSide

export async function getServerSideProps({ locale }) { const data = await serverSideTranslations(locale, ['apple', 'home']); return { props: data, }; } export default function IndexPage() { return <h1>Hi!< ...

Experiencing Difficulty Integrating MUI into NextJS 13 Application Router Despite Having Followed Tutorials

While configuring my Nextjs 13 App Router with MUI 5, I carefully followed the instructions provided at this link: https://mui.com/material-ui/guides/next-js-app-router/. My code closely resembles the sample code found here: https://github.com/mui/material ...

Resolve problems with implementing dynamic routes in Next.js

I have been learning about Next.js and I am struggling with understanding how to set up dynamic routing. I have the following setup: https://i.stack.imgur.com/uBPdm.png https://i.stack.imgur.com/YYSxn.png "use client" import React from "reac ...