#DevHack: Simple caching in Node.js Azure Functions

Development Devhack Azure Functions
post

This post is over a year old, some of this information may be out of date.

Azure Functions do not have an out-of-the-box caching mechanism. For caching, the recommended way would be to use a distributed cache like Azure Cache or Redis. These services each come with their price tag and might be too robust for the cache you want to create or need.

For Azure Function created with C#, you can use the good old memory cache. When your function is already warmed up, and processed data once, you can return results much quicker.

But what with Node.js?

The simplest option for Node.js JavaScript/TypeScript function is to use a library called node-cache.

The library provides a simple caching module that allows you to get, set, and more. It works very similarly to what you can do with memory cache.

Example:

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import * as NodeCache from 'node-cache';
const fncCache = new NodeCache();
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
// Check if there is a value in the cache
const cachedName = fncCache.get("name");
if (cachedName) {
context.res = {
// status: 200, /* Defaults to 200 */
body: `Cached name: ${cachedName}`
};
return;
}
// Read the provided name
const name = (req.query.name || (req.body && req.body.name));
// Set value in the cache
fncCache.set("name", name);
context.res = {
body: `Provided name: ${name}`
};
};
export default httpTrigger;

The code snippet is just a simple example, but this can be very useful. For example, when you want to fetch data and pass this to the function caller. Instead of calling the API each time the function gets invoked, you can now return cached data. It also allows you to specify on a global level or local/key level what the expiration time is. This expiration time is handy to keep your data fresh, but still do not have too many calls.

Want the next article?

Subscribe to the RSS feed, or follow me where I share new posts.

Related articles

Report issues or make changes on GitHub

Found a typo or issue in this article? Visit the GitHub repository to make changes or submit a bug report.

Comments

Elio Struyf

I build developer tools · Microsoft 365 architect · Speaker

Loading...

Let's build together

All your AI coding agents in one window

Present from VS Code

Manage content in VS Code

See all my projects →