Quickstart: Use Azure Cache for Redis in Node.js

In this quickstart, you incorporate Azure Cache for Redis into a Node.js app to have access to a secure, dedicated cache that is accessible from any application within Azure.

Prerequisites

For examples of using other Node.js clients, see the individual documentation for the Node.js clients listed at Node.js Redis clients.

Create a cache

  1. To create a cache, sign in to the Azure portal and select Create a resource.

    Create a resource is highlighted in the left navigation pane.

  2. On the Get Started page, type Azure Cache for Redis in the search box. Then, select Create.

    Screenshot of the Azure Marketplace with Azure Cache for Redis in the search box and create is highlighted with a red box.

  3. On the New Redis Cache page, configure the settings for your cache.

    Setting Choose a value Description
    Subscription Drop down and select your subscription. The subscription under which to create this new Azure Cache for Redis instance.
    Resource group Drop down and select a resource group, or select Create new and enter a new resource group name. Name for the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
    DNS name Enter a unique name. The cache name must be a string between 1 and 63 characters that contain only numbers, letters, or hyphens. The name must start and end with a number or letter, and can't contain consecutive hyphens. Your cache instance's host name is <DNS name>.redis.cache.windows.net.
    Location Drop down and select a location. Select a region near other services that use your cache.
    Cache SKU Drop down and select a SKU. The SKU determines the size, performance, and features parameters that are available for the cache. For more information, see Azure Cache for Redis Overview.
    Cache size Drop down and select a size of your cache For more information, see Azure Cache for Redis Overview.
  4. Select the Networking tab or select the Networking button at the bottom of the page.

  5. In the Networking tab, select your connectivity method.

  6. Select the Next: Advanced tab or select the Next: Advanced button on the bottom of the page to see the Advanced tab.

    Screenshot showing the Advanced tab in the working pane and the available option to select.

    • For Basic or Standard caches, toggle the selection for a non-TLS port. You can also select if you want to enable Microsoft Entra Authentication.
    • For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence. You can also select if you want to enable Microsoft Entra Authentication.
  7. Select the Next: Tags tab or select the Next: Tags button at the bottom of the page.

  8. Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  9. Select Review + create. You're taken to the Review + create tab where Azure validates your configuration.

  10. After the green Validation passed message appears, select Create.

It takes a while for a cache to create. You can monitor progress on the Azure Cache for Redis Overview page. When Status shows as Running, the cache is ready to use.

Retrieve host name, ports, and access keys from the Azure portal

To connect your Azure Cache for Redis server, the cache client needs the host name, ports, and a key for the cache. Some clients might refer to these items by slightly different names. You can get the host name, ports, and keys from the Azure portal.

  • To get the access keys, select Authentication from the Resource menu. Then, select the Access keys tab.

    Azure Cache for Redis keys

  • To get the host name and ports for your cache, select Overview from the Resource menu. The host name is of the form <DNS name>.redis.cache.windows.net.

    Azure Cache for Redis properties

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.

set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
set AZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Connect to the cache

The latest builds of node_redis provide support several connection options. 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. Use the command to install a redis package.

    `npm install redis`
    
  3. Add the following example JavaScript to the file.

    const redis = require("redis");
    
    // Environment variables for cache
    const cacheHostName = process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME;
    const cachePassword = process.env.AZURE_CACHE_FOR_REDIS_ACCESS_KEY;
    
    if(!cacheHostName) throw Error("AZURE_CACHE_FOR_REDIS_HOST_NAME is empty")
    if(!cachePassword) throw Error("AZURE_CACHE_FOR_REDIS_ACCESS_KEY is empty")
    
    async function testCache() {
    
        // Connection configuration
        const cacheConnection = redis.createClient({
            // rediss for TLS
            url: `rediss://${cacheHostName}:6380`,
            password: cachePassword
        });
    
        // Connect to Redis
        await cacheConnection.connect();
    
        // PING command
        console.log("\nCache command: PING");
        console.log("Cache response : " + await cacheConnection.ping());
    
        // GET
        console.log("\nCache command: GET Message");
        console.log("Cache response : " + await cacheConnection.get("Message"));
    
        // SET
        console.log("\nCache command: SET Message");
        console.log("Cache response : " + await cacheConnection.set("Message",
            "Hello! The cache is working from Node.js!"));
    
        // GET again
        console.log("\nCache command: GET Message");
        console.log("Cache response : " + await cacheConnection.get("Message"));
    
        // Client list, useful to see if connection list is growing...
        console.log("\nCache command: CLIENT LIST");
        console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
    
        // Disconnect
        cacheConnection.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/.

  4. Run the script with Node.js.

    node redistest.js
    
  5. 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
    

Clean up resources

If you continue to the next tutorial, can keep the resources created in this quickstart and reuse them. Otherwise, if you're finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.

Important

Deleting a resource group is irreversible and that the resource group and all the resources in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually instead of deleting the resource group.

  1. Sign in to the Azure portal and select Resource groups.

  2. In the Filter by name text box, enter the name of your resource group. The instructions for this article used a resource group named TestResources. On your resource group in the result list, select ... then Delete resource group.

    Delete Azure Resource group

  3. Confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select Delete.

  4. After a few moments, the resource group and all of its contained resources are deleted.

Get the sample code

Get the Node.js quickstart on GitHub.

Next steps

In this quickstart, you learned how to use Azure Cache for Redis from a Node.js application. Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.