Quickstart: Azure Key Vault secret client library for JavaScript (version 4)

Get started with the Azure Key Vault secret client library for JavaScript. Azure Key Vault is a cloud service that provides a secure store for secrets. You can securely store keys, passwords, certificates, and other secrets. Azure key vaults may be created and managed through the Azure portal. In this quickstart, you learn how to create, retrieve, and delete secrets from an Azure key vault using the JavaScript client library

Key Vault client library resources:

API reference documentation | Library source code | Package (npm)

For more information about Key Vault and secrets, see:

Prerequisites

This quickstart assumes you are running Azure CLI.

Sign in to Azure

  1. Run the login command.

    az login
    

    If the CLI can open your default browser, it will do so and load an Azure sign-in page.

    Otherwise, open a browser page at https://aka.ms/devicelogin and enter the authorization code displayed in your terminal.

  2. Sign in with your account credentials in the browser.

Create new Node.js application

Next, create a Node.js application that can be deployed to the Cloud.

  1. In a command shell, create a folder named key-vault-node-app:
mkdir key-vault-node-app
  1. Change to the newly created key-vault-node-app directory, and run 'init' command to initialize node project:
cd key-vault-node-app
npm init -y

Install Key Vault packages

From the console window, install the Azure Key Vault secrets library for Node.js.

npm install @azure/keyvault-secrets

Install the azure.identity package to authenticate to a Key Vault

npm install @azure/identity

Set environment variables

This application is using key vault name as an environment variable called KEY_VAULT_NAME.

Windows

set KEY_VAULT_NAME=<your-key-vault-name>

Windows PowerShell

$Env:KEY_VAULT_NAME="<your-key-vault-name>"

macOS or Linux

export KEY_VAULT_NAME=<your-key-vault-name>

Grant access to your key vault

Create an access policy for your key vault that grants secret permissions to your user account

az keyvault set-policy --name <YourKeyVaultName> --upn user@domain.com --secret-permissions delete get list set purge

Code examples

The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret.

Set up the app framework

  1. Create new text file and save it as 'index.js'

  2. Add require calls to load Azure and Node.js modules

  3. Create the structure for the program, including basic exception handling

const readline = require('readline');

function askQuestion(query) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });

    return new Promise(resolve => rl.question(query, ans => {
        rl.close();
        resolve(ans);
    }))
}

async function main() {
    
}

main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));

Add directives

Add the following directives to the top of your code:

const { DefaultAzureCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");

Authenticate and create a client

In this quickstart, logged in user is used to authenticate to key vault, which is preferred method for local development. For applications deployed to Azure, managed identity should be assigned to App Service or Virtual Machine, for more information, see Managed Identity Overview.

In below example, the name of your key vault is expanded to the key vault URI, in the format "https://<your-key-vault-name>.vault.azure.net". This example is using the 'DefaultAzureCredential()' class from Azure Identity Library, which allows us to use the same code across different environments with different options to provide identity. For more information about authenticating to Key Vault, see Developer's Guide.

Add the following code to 'main()' function

const keyVaultName = process.env["KEY_VAULT_NAME"];
const KVUri = "https://" + keyVaultName + ".vault.azure.net";

const credential = new DefaultAzureCredential();
const client = new SecretClient(KVUri, credential);

Save a secret

Now that your application is authenticated, you can put a secret into your keyvault using the setSecret method This requires a name for the secret - we're using "mySecret" in this sample.

await client.setSecret(secretName, secretValue);

Retrieve a secret

You can now retrieve the previously set value with the getSecret method.

const retrievedSecret = await client.getSecret(secretName);

Your secret is now saved as retrievedSecret.value.

Delete a secret

Finally, let's delete and purge the secret from your key vault with the beginDeleteSecret and purgeDeletedSecret methods.

const deletePoller = await client.beginDeleteSecret(secretName);
await deletePoller.pollUntilDone();
await client.purgeDeletedSecret(secretName);

Sample code

const { DefaultAzureCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");

const readline = require('readline');

function askQuestion(query) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });

    return new Promise(resolve => rl.question(query, ans => {
        rl.close();
        resolve(ans);
    }))
}

async function main() {

  const keyVaultName = process.env["KEY_VAULT_NAME"];
  const KVUri = "https://" + keyVaultName + ".vault.azure.net";

  const credential = new DefaultAzureCredential();
  const client = new SecretClient(KVUri, credential);

  const secretName = "mySecret";
  var secretValue = await askQuestion("Input the value of your secret > ");

  console.log("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "` ...");
  await client.setSecret(secretName, secretValue);

  console.log("Done.");

  console.log("Forgetting your secret.");
  secretValue = "";
  console.log("Your secret is '" + secretValue + "'.");

  console.log("Retrieving your secret from " + keyVaultName + ".");

  const retrievedSecret = await client.getSecret(secretName);

  console.log("Your secret is '" + retrievedSecret.value + "'.");

  console.log("Deleting your secret from " + keyVaultName + " ...");
  const deletePoller = await client.beginDeleteSecret(secretName);
  await deletePoller.pollUntilDone();
  console.log("Done.");
  
  console.log("Purging your secret from {keyVaultName} ...");
  await client.purgeDeletedSecret(secretName);
  
}

main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));

Test and verify

  1. Execute the following commands to run the app.

    npm install
    node index.js
    
  2. When prompted, enter a secret value. For example, mySecretPassword.

    A variation of the following output appears:

    Input the value of your secret > mySecretPassword
    Creating a secret in <your-unique-keyvault-name> called 'mySecret' with the value 'mySecretPassword' ... done.
    Forgetting your secret.
    Your secret is ''.
    Retrieving your secret from <your-unique-keyvault-name>.
    Your secret is 'mySecretPassword'.
    Deleting your secret from <your-unique-keyvault-name> ... done.  
    Purging your secret from <your-unique-keyvault-name> ... done.   
    

Next steps

In this quickstart, you created a key vault, stored a secret, and retrieved that secret. To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.