The KV library provides a Redis-like interface to interact with Azion’s KV Store. This library offers familiar Redis patterns including event-based error handling, connection management, and hash operations.

Go to Azion Libraries Overview

You can interact with the API using a client with Redis-like chaining patterns. The client supports both native runtime and API-based providers with automatic detection.

This is an example of how a .env file with your environment variables may look like:

Terminal window
AZION_TOKEN=<your-api-token>
AZION_DEBUG=true
VariableDescription
AZION_TOKENYour Azion API token.
AZION_DEBUGEnable debug mode (true/false).

Usage

Creating a client

Create a KV client using the Redis-like chaining pattern:

import { createClient } from 'azion/kv';
import type { KVClient } from 'azion/kv';
// Create a client with Redis-like chaining pattern
const client: KVClient = await createClient()
.on('error', (err) => console.log('KV Client Error', err))
.connect();

You can also create a client with custom options:

import { createClient } from 'azion/kv';
const client = await createClient({
namespace: 'my-namespace',
apiToken: 'my-token',
})
.on('error', (err) => console.error('KV Error:', err))
.connect();

Parameters:

ParameterTypeDescription
optionsKVClientOptions (optional)Configuration options for the client.
options.namespacestring (optional)The namespace to use for KV operations.
options.apiTokenstring (optional)The API token for authentication.

Returns:

Return TypeDescription
KVClientA client object with methods to interact with KV Store.

get

Retrieves a value by key.

const value = await client.get('my-key');
console.log(value);

Parameters:

ParameterTypeDescription
keystringThe key to retrieve.
optionsKVGetOptions (optional)Options for the get operation.

Returns:

Return TypeDescription
Promise<KVGetValue | null>The value or null if not found.

getWithMetadata

Retrieves a value along with its metadata.

const result = await client.getWithMetadata('my-key');
console.log(result.value, result.metadata);

Parameters:

ParameterTypeDescription
keystringThe key to retrieve.
optionsKVGetOptions (optional)Options for the get operation.

Returns:

Return TypeDescription
Promise<KVGetResult>An object containing the value and metadata.

set

Stores a value with an optional expiration and metadata.

// Simple set
await client.set('my-key', 'my-value');
// Set with options
await client.set('my-key', 'my-value', {
expiration: {
type: 'EX',
value: 10, // 10 seconds
},
metadata: { userId: '123' },
});

Parameters:

ParameterTypeDescription
keystringThe key to store.
valueKVValueThe value to store.
optionsKVSetOptions (optional)Options for the set operation.

The KVSetOptions object supports the following properties:

OptionTypeDescription
expirationobject (optional)Expiration configuration.
expiration.type'EX' | 'PX' | 'EXAT' | 'PXAT'Expiration type.
expiration.valuenumberExpiration value.
metadataobject (optional)Metadata to associate with the key.

Expiration types:

TypeDescription
EXExpire in seconds from now.
PXExpire in milliseconds from now.
EXATExpire at a specific Unix timestamp (seconds).
PXATExpire at a specific Unix timestamp (milliseconds).

Returns:

Return TypeDescription
Promise<void>Resolves when the operation is complete.

delete / del

Deletes a key from the store.

await client.delete('my-key');
// or
await client.del('my-key');

Parameters:

ParameterTypeDescription
keystringThe key to delete.

Returns:

Return TypeDescription
Promise<void>Resolves when the operation is complete.

Hash operations

The KV library supports Redis-like hash operations for storing field-value pairs.

hSet / HSET

Sets a field in a hash.

await client.hSet('my-key', 'field', 'value');
await client.HSET('my-key', 'field', 'value');

Parameters:

ParameterTypeDescription
keystringThe hash key.
fieldstringThe field name.
valueKVValueThe value to store.

Returns:

Return TypeDescription
Promise<void>Resolves when the operation is complete.

hGetAll / HGETALL

Gets all fields and values from a hash.

const result = await client.hGetAll('my-key');
const result = await client.HGETALL('my-key');

Parameters:

ParameterTypeDescription
keystringThe hash key.

Returns:

Return TypeDescription
Promise<KVGetValue | null>The hash data or null if not found.

hVals / HVALS

Gets all values from a hash.

const result = await client.hVals('my-key');
const result = await client.HVALS('my-key');

Parameters:

ParameterTypeDescription
keystringThe hash key.

Returns:

Return TypeDescription
Promise<KVGetValue[] | null>An array of values or null if not found.

Connection management

disconnect / quit

Disconnects from the KV store.

await client.disconnect();
// or
await client.quit();

Returns:

Return TypeDescription
Promise<void>Resolves when disconnected.

Provider detection

getProviderType

Returns the current provider type being used.

const providerType = client.getProviderType();
console.log(providerType); // 'native' or 'api'

Returns:

Return TypeDescription
'native' | 'api'The provider type.

The client automatically detects the environment:

  • native: Used when running in Azion Runtime (Functions).
  • api: Used when running outside of Azion Runtime (local development, external servers).

Error handling

The KV client uses an event-based error handling pattern similar to Redis:

const client = await createClient()
.on('error', (err) => {
console.error('KV Client Error:', err);
// Handle error appropriately
})
.connect();

You can also use try-catch for individual operations:

try {
const value = await client.get('my-key');
} catch (error) {
console.error('Failed to get value:', error);
}

Complete example

import { createClient } from 'azion/kv';
async function main() {
// Create and connect client
const client = await createClient({
namespace: 'my-namespace',
})
.on('error', (err) => console.error('KV Error:', err))
.connect();
// Store a value with expiration
await client.set('user:123', JSON.stringify({ name: 'John', role: 'admin' }), {
expiration: { type: 'EX', value: 3600 }, // 1 hour
metadata: { createdBy: 'system' },
});
// Retrieve the value
const userData = await client.get('user:123');
console.log('User data:', userData);
// Get with metadata
const result = await client.getWithMetadata('user:123');
console.log('Value:', result.value);
console.log('Metadata:', result.metadata);
// Hash operations
await client.hSet('config', 'theme', 'dark');
await client.hSet('config', 'language', 'en');
const config = await client.hGetAll('config');
console.log('Config:', config);
// Check provider type
console.log('Provider:', client.getProviderType());
// Delete and disconnect
await client.delete('user:123');
await client.disconnect();
}
main();

Types

These are the types used by the KV library:

KVClient

The main client interface for KV operations.

MethodParametersReturn TypeDescription
onevent: 'error', handler: (error: Error) => voidthisRegister error event handler (chainable).
connect-Promise<this>Connect to KV store (chainable).
getkey: string, options?: KVGetOptionsPromise<KVGetValue | null>Get a value.
getWithMetadatakey: string, options?: KVGetOptionsPromise<KVGetResult>Get value with metadata.
setkey: string, value: KVValue, options?: KVSetOptionsPromise<void>Set a value.
deletekey: stringPromise<void>Delete a key.
delkey: stringPromise<void>Alias for delete.
disconnect-Promise<void>Disconnect from store.
quit-Promise<void>Alias for disconnect.
hSetkey: string, field: string, value: KVValuePromise<void>Set hash field.
HSETkey: string, field: string, value: KVValuePromise<void>Alias for hSet.
hGetAllkey: stringPromise<KVGetValue | null>Get all hash fields.
HGETALLkey: stringPromise<KVGetValue | null>Alias for hGetAll.
hValskey: stringPromise<KVGetValue[] | null>Get all hash values.
HVALSkey: stringPromise<KVGetValue[] | null>Alias for hVals.
getProviderType-'native' | 'api'Get current provider type.

KVClientOptions

Configuration options for the KV client.

PropertyTypeDescription
namespacestring (optional)The namespace for KV operations.
apiTokenstring (optional)The API token for authentication.

KVSetOptions

Options for set operations.

PropertyTypeDescription
expiration{ type: 'EX' | 'PX' | 'EXAT' | 'PXAT', value: number } (optional)Expiration configuration.
metadataobject (optional)Metadata to associate with the key.

KVGetResult

Result from getWithMetadata operation.

PropertyTypeDescription
valueKVGetValue | nullThe retrieved value.
metadataobject | nullThe associated metadata.