Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Prepare Azure environments for new workloads—subscriptions, networking, identity, and landing zones
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/services/app-service/templates/recipes/redis/source/nodejs.md
1# Redis Recipe — Node.js — REFERENCE ONLY23## ioredis with Token Refresh45### npm Packages67```bash8npm install ioredis @azure/identity9```1011### Cache Module1213Create `src/cache.js`:1415```javascript16const Redis = require("ioredis");17const { DefaultAzureCredential } = require("@azure/identity");1819const credential = new DefaultAzureCredential();20const TOKEN_SCOPE = "https://redis.azure.com/.default";21// Redis ACL auth requires both username and token as password22const REDIS_USERNAME = "default";23const TOKEN_REFRESH_MARGIN = 5 * 60 * 1000; // 5 minutes in ms2425let _client = null;26let _tokenExpiry = 0;2728async function getToken() {29const tok = await credential.getToken(TOKEN_SCOPE);30_tokenExpiry = tok.expiresOnTimestamp;31return tok.token;32}3334async function getRedisClient() {35const now = Date.now();36if (_client && now < _tokenExpiry - TOKEN_REFRESH_MARGIN) {37return _client;38}3940// Token expired or about to expire — create a new client with a fresh token41if (_client) {42_client.disconnect();43_client = null;44}4546const token = await getToken();47_client = new Redis({48host: process.env.REDIS_HOST,49port: parseInt(process.env.REDIS_PORT || "6380"),50tls: { servername: process.env.REDIS_HOST },51username: REDIS_USERNAME,52password: token,53lazyConnect: true,54});55await _client.connect();56return _client;57}5859module.exports = { getRedisClient };60```6162> ⚠️ Entra ID tokens expire in ~1 hour. `getRedisClient()` recreates the connection with a fresh token when the current one is within 5 minutes of expiry. Always call `getRedisClient()` before each operation rather than caching the client reference long-term.6364### Usage6566```javascript67const { getRedisClient } = require("./cache");6869app.get("/api/cached", async (req, res) => {70const client = await getRedisClient();71let value = await client.get("my-key");72if (!value) {73value = "computed-value";74await client.setex("my-key", 300, value); // TTL 5 minutes75}76res.json({ value });77});78```7980## Files to Modify8182| File | Action |83|------|--------|84| `src/cache.js` | Create — Redis client with token refresh |85| `src/index.js` | Modify — use getRedisClient() |86| `package.json` | Modify — add ioredis, @azure/identity |87