Skip to content

Latest commit

 

History

History
720 lines (511 loc) · 27.4 KB

nodejs-get-started.md

File metadata and controls

720 lines (511 loc) · 27.4 KB
titledescriptionms.devlangms.topicms.datems.customzone_pivot_groupsappliesto
Quickstart: Use Azure Cache for Redis in Node.js
In this quickstart, learn how to use Azure Managed Redis or Azure Cache for Redis with Node.js and node_redis.
javascript
quickstart
06/04/2024
mvc, devx-track-js, mode-api, engagement-fy23, ignite-2024
redis-type
✅ Azure Managed Redis
✅ Azure Cache for Redis

Quickstart: Use Azure Redis in Node.js

In this quickstart, you incorporate Azure Managed Redis (preview) or Azure Cache for Redis into a Node.js app. The app has access to a secure, dedicated cache that is accessible from any application within Azure.

Prerequisites

::: zone pivot="azure-managed-redis"

Create an Azure Managed Redis (preview) instance

[!INCLUDE managed-redis-create]

::: zone-end

::: zone pivot="azure-cache-redis"

Create an Azure Cache for Redis instance

[!INCLUDE redis-cache-create]

::: zone-end

Install the node-redis client library

The node-redis library is the primary Node.js client for Redis. You can install the client with npm by using the following command:

npm install redis

::: zone pivot="azure-managed-redis"

Create a Node.js app to access a cache

Create a Node.js app that uses either Microsoft Entra ID or access keys to connect to an Azure Managed Redis (preview) instance. We recommend you use Microsoft Entra ID.

[!INCLUDE cache-entra-access]

Install the JavaScript Azure Identity client library

The Microsoft Authentication Library (MSAL) allows you to acquire security tokens from Microsoft identity to authenticate users. There's a JavaScript Azure identity client library available that uses MSAL to provide token authentication support. Install this library using npm:

npm install @azure/identity

Create a new Node.js app using Microsoft Entra ID

  1. Add environment variables for your Host name and Service Principal ID, which is the object ID of your Microsoft Entra ID service principal or user. In the Azure portal, look for the Username.

    setAZURE_MANAGED_REDIS_HOST_NAME=contosoCache setREDIS_SERVICE_PRINCIPAL_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  2. Create a new script file named redistest.js.

  3. Add the following example JavaScript to the file. This code shows you how to connect to an Azure Managed Redis instance using the cache host name and key environment variables. The code also stores and retrieves a string value in the cache. The PING and CLIENT LIST commands are also executed. For more examples of using Redis with the node-redis client, see https://redis.js.org/.

    const{ createClient }=require("redis");const{ DefaultAzureCredential }=require("@azure/identity");asyncfunctionmain(){// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.constcredential=newDefaultAzureCredential();constredisScope="https://redis.azure.com/.default";// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.letaccessToken=awaitcredential.getToken(redisScope);console.log("access Token",accessToken);// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.constcacheConnection=createClient({username: process.env.REDIS_SERVICE_PRINCIPAL_ID,password: accessToken.token,url: `redis://${process.env.AZURE_MANAGED_REDIS_HOST_NAME}:10000`,pingInterval: 100000,socket: {tls: true,keepAlive: 0},});cacheConnection.on("error",(err)=>console.log("Redis Client Error",err));awaitcacheConnection.connect();// PING commandconsole.log("\nCache command: PING");console.log("Cache response : "+awaitcacheConnection.ping());// SETconsole.log("\nCache command: SET Message");console.log("Cache response : "+awaitcacheConnection.set("Message","Hello! The cache is working from Node.js!"));// GETconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// Client list, useful to see if connection list is growing...console.log("\nCache command: CLIENT LIST");console.log("Cache response : "+awaitcacheConnection.sendCommand(["CLIENT","LIST"]));cacheConnection.disconnect();return"Done"}main().then((result)=>console.log(result)).catch(ex=>console.log(ex));
  4. Run the script with Node.js.

    node redistest.js
  5. The output of your code looks like this.

    Cache command: PING Cache response : PONG Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: SET Message Cache response : OK Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: CLIENT LIST Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6 Done

Create a sample JavaScript app with reauthentication

Microsoft Entra ID access tokens have a limited lifespan, averaging 75 minutes. In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using JavaScript.

  1. Create a new script file named redistestreauth.js.

  2. Add the following example JavaScript to the file.

    const{ createClient }=require("redis");const{ DefaultAzureCredential }=require("@azure/identity");asyncfunctionreturnPassword(credential){constredisScope="https://redis.azure.com/.default";// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.returncredential.getToken(redisScope);}asyncfunctionmain(){// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.constcredential=newDefaultAzureCredential();letaccessToken=awaitreturnPassword(credential);// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.letcacheConnection=createClient({username: process.env.REDIS_SERVICE_PRINCIPAL_ID,password: accessToken.token,url: `redis://${process.env.AZURE_MANAGED_REDIS_HOST_NAME}:10000`,pingInterval: 100000,socket: {tls: true,keepAlive: 0},});cacheConnection.on("error",(err)=>console.log("Redis Client Error",err));awaitcacheConnection.connect();for(leti=0;i<3;i++){try{// PING commandconsole.log("\nCache command: PING");console.log("Cache response : "+awaitcacheConnection.ping());// SETconsole.log("\nCache command: SET Message");console.log("Cache response : "+awaitcacheConnection.set("Message","Hello! The cache is working from Node.js!"));// GETconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// Client list, useful to see if connection list is growing...console.log("\nCache command: CLIENT LIST");console.log("Cache response : "+awaitcacheConnection.sendCommand(["CLIENT","LIST"]));break;}catch(e){console.log("error during redis get",e.toString());if((accessToken.expiresOnTimestamp<=Date.now())||(redis.status==="end"||"close")){awaitredis.disconnect();accessToken=awaitreturnPassword(credential);cacheConnection=createClient({username: process.env.REDIS_SERVICE_PRINCIPAL_ID,password: accessToken.token,url: `redis://${process.env.AZURE_MANAGED_REDIS_HOST_NAME}:10000`,pingInterval: 100000,socket: {tls: true,keepAlive: 0},});}}}}main().then((result)=>console.log(result)).catch(ex=>console.log(ex));
  3. Run the script with Node.js.

    node redistestreauth.js
  4. The output of your code looks like this.

     Cache command: PING Cache response : PONG Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: SET Message Cache response : OK Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: CLIENT LIST Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6 

Note

For additional examples of using Microsoft Entra ID to authenticate to Redis using the node-redis library, please see this GitHub repo

[!INCLUDE redis-access-key-alert]

[!INCLUDE redis-cache-access-keys]

Add environment variables for your HOST NAME and Primary access key. Use these variables from your code instead of including the sensitive information directly in your code.

setAZURE_MANAGED_REDIS_HOST_NAME=contosoCache setAZURE_MANAGED_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Connect to the cache

Note

Don't create a new connection for each operation in your code. Instead, reuse connections as much as possible.

Create a new Node.js app

  1. Create a new script file named redistest.js.

  2. Add the following example JavaScript to the file.

    constredis=require("redis");// Environment variables for cacheconstcacheHostName=process.env.AZURE_MANAGED_REDIS_HOST_NAME;constcachePassword=process.env.AZURE_MANAGED_REDIS_ACCESS_KEY;if(!cacheHostName)throwError("AZURE_MANAGED_REDIS_HOST_NAME is empty")if(!cachePassword)throwError("AZURE_MANAGED_REDIS_ACCESS_KEY is empty")asyncfunctiontestCache(){// Connection configurationconstcacheConnection=redis.createClient({// redis for TLSurl: `redis://${cacheHostName}:10000`,password: cachePassword});// Connect to RedisawaitcacheConnection.connect();// PING commandconsole.log("\nCache command: PING");console.log("Cache response : "+awaitcacheConnection.ping());// GETconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// SETconsole.log("\nCache command: SET Message");console.log("Cache response : "+awaitcacheConnection.set("Message","Hello! The cache is working from Node.js!"));// GET againconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// Client list, useful to see if connection list is growing...console.log("\nCache command: CLIENT LIST");console.log("Cache response : "+awaitcacheConnection.sendCommand(["CLIENT","LIST"]));// DisconnectcacheConnection.disconnect()return"Done"}testCache().then((result)=>console.log(result)).catch(ex=>console.log(ex));

    This code shows you how to connect to an Azure Cache for Redis instance using the cache host name and key environment variables. The code also stores and retrieves a string value in the cache. The PING and CLIENT LIST commands are also executed. For more examples of using Redis with the node_redis client, see https://redis.js.org/.

  3. Run the script with Node.js.

    node redistest.js
  4. Example the output.

    Cache command: PING Cache response : PONG Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: SET Message Cache response : OK Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: CLIENT LIST Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6 Done

::: zone-end

::: zone pivot="azure-cache-redis"

Create a Node.js app to access a cache

Create a Node.js app that uses either Microsoft Entra ID or access keys to connect to an Azure Cache for Redis. We recommend you use Microsoft Entra ID.

[!INCLUDE cache-entra-access]

Install the JavaScript Azure Identity client library

The Microsoft Authentication Library (MSAL) allows you to acquire security tokens from Microsoft identity to authenticate users. There's a JavaScript Azure identity client library available that uses MSAL to provide token authentication support. Install this library using npm:

npm install @azure/identity

Create a new Node.js app using Microsoft Entra ID

  1. Add environment variables for your Host name and Service Principal ID, which is the object ID of your Microsoft Entra ID service principal or user. In the Azure portal, look for the Username.

    setAZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache setREDIS_SERVICE_PRINCIPAL_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  2. Create a new script file named redistest.js.

  3. Add the following example JavaScript to the file. This code shows you how to connect to an Azure Cache for Redis instance using the cache host name and key environment variables. The code also stores and retrieves a string value in the cache. The PING and CLIENT LIST commands are also executed. For more examples of using Redis with the node-redis client, see https://redis.js.org/.

    const{ createClient }=require("redis");const{ DefaultAzureCredential }=require("@azure/identity");asyncfunctionmain(){// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.constcredential=newDefaultAzureCredential();constredisScope="https://redis.azure.com/.default";// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.letaccessToken=awaitcredential.getToken(redisScope);console.log("access Token",accessToken);// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.constcacheConnection=createClient({username: process.env.REDIS_SERVICE_PRINCIPAL_ID,password: accessToken.token,url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,pingInterval: 100000,socket: {tls: true,keepAlive: 0},});cacheConnection.on("error",(err)=>console.log("Redis Client Error",err));awaitcacheConnection.connect();// PING commandconsole.log("\nCache command: PING");console.log("Cache response : "+awaitcacheConnection.ping());// SETconsole.log("\nCache command: SET Message");console.log("Cache response : "+awaitcacheConnection.set("Message","Hello! The cache is working from Node.js!"));// GETconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// Client list, useful to see if connection list is growing...console.log("\nCache command: CLIENT LIST");console.log("Cache response : "+awaitcacheConnection.sendCommand(["CLIENT","LIST"]));cacheConnection.disconnect();return"Done"}main().then((result)=>console.log(result)).catch(ex=>console.log(ex));
  4. Run the script with Node.js.

    node redistest.js
  5. The output of your code looks like this.

    Cache command: PING Cache response : PONG Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: SET Message Cache response : OK Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: CLIENT LIST Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6 Done

Create a sample JavaScript app with reauthentication

Microsoft Entra ID access tokens have a limited lifespan, averaging 75 minutes. In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using JavaScript.

  1. Create a new script file named redistestreauth.js.

  2. Add the following example JavaScript to the file.

    const{ createClient }=require("redis");const{ DefaultAzureCredential }=require("@azure/identity");asyncfunctionreturnPassword(credential){constredisScope="https://redis.azure.com/.default";// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.returncredential.getToken(redisScope);}asyncfunctionmain(){// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.constcredential=newDefaultAzureCredential();letaccessToken=awaitreturnPassword(credential);// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.letcacheConnection=createClient({username: process.env.REDIS_SERVICE_PRINCIPAL_ID,password: accessToken.token,url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,pingInterval: 100000,socket: {tls: true,keepAlive: 0},});cacheConnection.on("error",(err)=>console.log("Redis Client Error",err));awaitcacheConnection.connect();for(leti=0;i<3;i++){try{// PING commandconsole.log("\nCache command: PING");console.log("Cache response : "+awaitcacheConnection.ping());// SETconsole.log("\nCache command: SET Message");console.log("Cache response : "+awaitcacheConnection.set("Message","Hello! The cache is working from Node.js!"));// GETconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// Client list, useful to see if connection list is growing...console.log("\nCache command: CLIENT LIST");console.log("Cache response : "+awaitcacheConnection.sendCommand(["CLIENT","LIST"]));break;}catch(e){console.log("error during redis get",e.toString());if((accessToken.expiresOnTimestamp<=Date.now())||(redis.status==="end"||"close")){awaitredis.disconnect();accessToken=awaitreturnPassword(credential);cacheConnection=createClient({username: process.env.REDIS_SERVICE_PRINCIPAL_ID,password: accessToken.token,url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,pingInterval: 100000,socket: {tls: true,keepAlive: 0},});}}}}main().then((result)=>console.log(result)).catch(ex=>console.log(ex));
  3. Run the script with Node.js.

    node redistestreauth.js
  4. The output of your code looks like this.

     Cache command: PING Cache response : PONG Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: SET Message Cache response : OK Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: CLIENT LIST Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6 

Note

For additional examples of using Microsoft Entra ID to authenticate to Redis using the node-redis library, please see this GitHub repo

[!INCLUDE redis-cache-access-keys]

Add environment variables for your HOST NAME and Primary access key. Use these variables from your code instead of including the sensitive information directly in your code.

setAZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache setAZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Connect to the cache

Note

Don't create a new connection for each operation in your code. Instead, reuse connections as much as possible.

Create a new Node.js app

  1. Create a new script file named redistest.js.

  2. Add the following example JavaScript to the file.

    constredis=require("redis");// Environment variables for cacheconstcacheHostName=process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME;constcachePassword=process.env.AZURE_CACHE_FOR_REDIS_ACCESS_KEY;if(!cacheHostName)throwError("AZURE_CACHE_FOR_REDIS_HOST_NAME is empty")if(!cachePassword)throwError("AZURE_CACHE_FOR_REDIS_ACCESS_KEY is empty")asyncfunctiontestCache(){// Connection configurationconstcacheConnection=redis.createClient({// redis for TLSurl: `redis://${cacheHostName}:6380`,password: cachePassword});// Connect to RedisawaitcacheConnection.connect();// PING commandconsole.log("\nCache command: PING");console.log("Cache response : "+awaitcacheConnection.ping());// GETconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// SETconsole.log("\nCache command: SET Message");console.log("Cache response : "+awaitcacheConnection.set("Message","Hello! The cache is working from Node.js!"));// GET againconsole.log("\nCache command: GET Message");console.log("Cache response : "+awaitcacheConnection.get("Message"));// Client list, useful to see if connection list is growing...console.log("\nCache command: CLIENT LIST");console.log("Cache response : "+awaitcacheConnection.sendCommand(["CLIENT","LIST"]));// DisconnectcacheConnection.disconnect()return"Done"}testCache().then((result)=>console.log(result)).catch(ex=>console.log(ex));

    This code shows you how to connect to an Azure Cache for Redis instance using the cache host name and key environment variables. The code also stores and retrieves a string value in the cache. The PING and CLIENT LIST commands are also executed. For more examples of using Redis with the node_redis client, see https://redis.js.org/.

  3. Run the script with Node.js.

    node redistest.js
  4. Example the output.

    Cache command: PING Cache response : PONG Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: SET Message Cache response : OK Cache command: GET Message Cache response : Hello! The cache is working from Node.js! Cache command: CLIENT LIST Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6 Done

::: zone-end

[!INCLUDE cache-delete-resource-group]

Get the sample code

Get the Node.js quickstart on GitHub.

Related content

In this quickstart, you learned how to use either Azure Managed Redis (preview) or Azure Cache for Redis from a Node.js application. Learn more about the Azure Redis offerings:

close