paint-brush
How to Create and Connecting Redis to a Serverless Node.js App on Azureby@nuralem
714 reads
714 reads

How to Create and Connecting Redis to a Serverless Node.js App on Azure

by Nuralem AbizovJune 12th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article, we'll learn how to deploy a serverless Node.js application on Microsoft Azure. We'll also learn about Redis, a NoSQL key-value store used as a database, cache, and message broker. We will also test the setup by connecting our application to Redis.
featured image - How to Create and Connecting Redis to a Serverless Node.js App on Azure
Nuralem Abizov HackerNoon profile picture


Hello, everyone! Today, we'll be diving into the fascinating world of software development, specifically dealing with a serverless Node.js application, Microsoft Azure, and Redis. These tools may sound intimidating, especially if you're new to software development, but I assure you, with some guidance, they are quite manageable. So, let's buckle up and get ready to learn.


Content Overview

  1. Introduction to Redis, Node.js, and Azure
  2. Setting up Node.js with Azure
  3. Installing Redis
  4. Connecting Node.js with Redis
  5. Testing the setup


Introduction to Redis, Node.js, and Azure

  • Redis is an open-source, in-memory data structure store used as a database, cache, and message broker. It's a NoSQL key-value store that's excellent for handling data with high velocity or volume.


  • Node.js is a runtime environment for executing JavaScript code server-side. It's used for building scalable and efficient network applications.


  • Azure is Microsoft's cloud computing platform and service, where we'll be deploying our Node.js application. Specifically, we'll use Azure Web App, a serverless computing service that allows you to run your code without provisioning or managing servers.


Setting up Node.js with Azure

For setting up all the required resources, I briefly explained in my previous article How to Deploy a Serverless Node.js Application on Azure.


Installing Redis

We need to install the Redis package on the Node.js project:

npm install redis


Then, we need to add some code to app.js file:

import redis from 'redis';
import { createServer } from 'http';


// Create an redis conn.
const client = redis.createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();

// For test.
await client.set('testKey', 'Hackernoon!');
const value = await client.get('testKey');

const server = createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end(`Hello, ${value}\n`);
});

server.listen(8080, '0.0.0.0', () => {
    console.log('Server running at http://0.0.0.0:8080/');
});


In package.json we need to add type: module:

{
  "name": "hackernoon",
  "version": "1.0.0",
  "type": "module",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "redis": "^4.6.7"
  }
}



Deploy it to the cloud and click “Start streaming logs“ (Img 1).



Img 1. Get some logs from Azure Web App.


Don’t forget to open the URL in the browser, it will turn on our web app after deployment.


On the logs stream you will see:

Redis Client Error Error: connect ECONNREFUSED ::1:6379


Now, we are ready to create a Redis app inside Azure and connect it.


Connecting Node.js with Redis


Search for Redis. On the Services, you will see “Azure Cache for Redis“ (Img 2).

Img2. Azure Cache for Redis.


Click on “Create Redis cache“. You should choose the resource group that is using your Web App (Img 4).



Img 3. Create Redis cache.



Img 4. Settings.


Create a resource and wait some time. Usually, it takes several minutes to complete. Then go to the resource “Overview” page and copy “Hostname” and paste it to the code":


import redis from "redis";
import { createServer } from "http";

// Create an redis conn.
const client = redis.createClient({
  url: "redis://hackernoon.redis.cache.windows.net",
  password: "<Your PRIMARY password from Azure Redis Resource>",
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();

// For test.
await client.set("testKey", "Hackernoon!");
const value = await client.get("testKey");

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end(`Hello, ${value}\n`);
});

server.listen(8080, "0.0.0.0", () => {
  console.log("Server running at http://0.0.0.0:8080/");
});


Password value you can find in “Access keys“ (Img 5).



Img 5. Access keys.


Also, go to Advanced settings, which is below “Access keys“ and put “No“ to Allow access only via SSL“. It will enable the Redis cache to work via the 6379 port.


Testing the setup

Finally, test your setup locally by running your Nodejs with the yarn start command. Your function should be able to access your Azure Redis instance. For deployment, push your project to Azure, and it should connect to the Azure Redis Cache.


That's it! You've successfully created a Redis instance and connected it to a serverless Node.js application on Azure. Remember, Don’t make db, redis, and other resources to be public, and remember to use SSL. Try to create a closed virtual network and use it. Close everything if possible inside your private network.


This guide is only for testing and learning. Practice is key when it comes to software development. Don't hesitate to tinker around with different settings and functionalities of Redis, Node.js, and Azure. The more you experiment, the better you understand.


Happy coding!