Skip to content
Learni
View all tutorials
Azure

How to Integrate Azure Key Vault into Your Node.js Apps in 2026

Lire en français

Introduction

Azure Key Vault is a Microsoft Azure cloud service designed to securely store and manage cryptographic keys, secrets (like passwords and connection strings), and certificates. In 2026, with proliferating regulations like GDPR and stricter security audits, skipping Key Vault leaves your apps vulnerable to major data breaches.

Why use it? Picture your API secrets (Stripe, SendGrid) hardcoded in source code: one accidental Git commit spells disaster. Key Vault centralizes everything, controls access via RBAC or policies, and automates rotations. This intermediate tutorial walks you through creating a vault, adding secrets, and consuming them in a Node.js app with the official SDK. By the end, you'll have a working Express API that dynamically fetches secure configs. Ready to level up your deployment security?

Prerequisites

  • Free Azure account (includes $200 credit for testing)
  • Azure CLI version 2.60+ installed
  • Node.js 20+ and npm/yarn
  • Basic knowledge of TypeScript and Azure (intermediate level)
  • VS Code with Azure and TypeScript extensions

Create the Resource Group and Key Vault

terminal
# Log in to Azure (use 'az login' in your browser)
az login

# Create a resource group (replace 'francecentral' with your region)
az group create --name rg-keyvault-demo --location francecentral

# Create the Key Vault with purge protection enabled (90-day recovery)
az keyvault create --name kv-demo-2026-unik --resource-group rg-keyvault-demo --location francecentral --enable-purge-protection true --enable-soft-delete true

# Verify creation
echo "Vault URI: $(az keyvault show --name kv-demo-2026-unik --query vaultUri -o tsv)"

This script sets up a resource group and Key Vault with anti-deletion protections (soft-delete and purge). Replace 'kv-demo-2026-unik' with a globally unique name. The displayed URI will be used for SDK access. Pitfall: Commands fail without prior login; always test the URI with 'az keyvault show'.

Configure Vault Access

Before adding secrets, define who can access them. For this tutorial, we'll use Azure CLI for quick access (via 'az login'), then DefaultAzureCredential in the Node.js app—perfect for dev/test/prod with Managed Identity in deployments. Avoid static access keys: prioritize managed identities.

Add a Secret to Key Vault

terminal
# Get the ID of the signed-in user (to authorize access)
USER_OBJECT_ID=$(az ad signed-in-user show --query id -o tsv)

# Grant Get/List access for this user
az keyvault set-policy --name kv-demo-2026-unik --upn $(az ad signed-in-user show --query userPrincipalName -o tsv) --secret-permissions get list

# Add a secret (example: fake API key)
az keyvault secret set --vault-name kv-demo-2026-unik --name "api-stripe-key" --value "sk_test_123456789abcdef"

# List secrets to verify
az keyvault secret list --vault-name kv-demo-2026-unik

We grant minimal permissions (get/list) to the signed-in user via RBAC-like policy. The secret is stored encrypted. Note: In production, use AD groups or Managed Identities; never hardcode real values here.

Prepare the Node.js Application

Let's build an Express app that fetches the secret on startup and uses it in a route. The @azure/keyvault-secrets + @azure/identity SDKs handle authentication automatically via CLI login or environment variables.

Initialize package.json

package.json
{
  "name": "keyvault-demo",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.js",
    "dev": "tsx watch index.ts"
  },
  "dependencies": {
    "express": "^4.19.2",
    "@azure/keyvault-secrets": "^1.0.0",
    "@azure/identity": "^3.0.0",
    "dotenv": "^16.4.5"
  },
  "devDependencies": {
    "@types/express": "^4.17.21",
    "tsx": "^4.7.0",
    "typescript": "^5.5.3"
  }
}

This package.json includes the official Azure SDKs and Express. 'tsx' enables hot-reload for TypeScript. Run 'npm install' after creating the project folder. Pitfall: Enable ESM with 'type: module' for modern Azure imports.

Build the App to Retrieve the Secret

index.ts
import express from 'express';
import { DefaultAzureCredential } from '@azure/identity';
import { SecretClient } from '@azure/keyvault-secrets';

const app = express();
const port = 3000;

// URI du Key Vault (remplacez par le vôtre)
const vaultUrl = 'https://kv-demo-2026-unik.vault.azure.net/';
const secretName = 'api-stripe-key';

let stripeKey: string;

async function loadSecret() {
  const credential = new DefaultAzureCredential();
  const client = new SecretClient(vaultUrl, credential);
  try {
    const secret = await client.getSecret(secretName);
    stripeKey = secret.value || '';
    console.log('✅ Secret chargé avec succès');
  } catch (error) {
    console.error('❌ Erreur chargement secret:', error);
    process.exit(1);
  }
}

app.get('/stripe-status', (req, res) => {
  res.json({ status: 'OK', keyPrefix: stripeKey?.slice(0, 10) + '...' });
});

(async () => {
  await loadSecret();
  app.listen(port, () => {
    console.log(`🚀 Serveur sur http://localhost:${port}`);
  });
})();

The app uses DefaultAzureCredential (detects az login, env vars, Managed ID). On startup, it fetches the secret and uses it in a secure route (value masked). Run with 'npm run dev'. Pitfall: Check permissions; without 'az login', it falls back to env vars like AZURE_CLIENT_ID.

Test the App Locally

terminal
cd keyvault-demo
npm install
npm run dev

# In another terminal, test
curl http://localhost:3000/stripe-status

# Cleanup (optional)
az keyvault purge --name kv-demo-2026-unik --location francecentral
ez group delete --name rg-keyvault-demo --yes --no-wait

Install, start, and test the endpoint. The returned JSON confirms the secret loaded (prefix masked). For cleanup, purge after 90-day soft-delete. Note: In CI/CD, set up env vars or OIDC for credentials.

Best Practices

  • Minimal permissions: Use 'get' only, not 'set', for runtime apps.
  • Automatic rotation: Set up via Azure Portal for critical secrets (e.g., 90 days).
  • Monitoring: Enable Azure Monitor + Sentinel for access audits.
  • In production: Deploy with Managed Identity (Azure App Service/Functions) instead of service principals.
  • Cache secrets: In Node.js, use Redis to avoid repeated vault calls.

Common Errors to Avoid

  • 401 Unauthorized: Check 'az keyvault set-policy' or assigned Managed ID.
  • Vault not found: Incorrectly copied URI (must end in '/').
  • DefaultAzureCredential fails: No local 'az login'; set AZURE_TENANT_ID etc.
  • Secrets in plain logs: Never console.log(secret.value) in production!

Next Steps

Master private HSMs with Key Vault Premium. Explore the Keys API for encryption. For .NET/C#, check the official SDK. Sign up for our Learni Azure trainings: includes AZ-204 certification. Official docs: Azure Key Vault.