@vercel/kv
Vercel KV is a durable Redis database that enables you to store and retrieve simple key-value data structures globally at the edge.Vercel KV is available on Hobby and Pro plans
Every supported Redis command can be executed with the Vercel KV SDK by calling it as a method. For example, to set a key value you'd call kv.set()
, and to increment a key value you'd call kv.incr()
.
This page will teach you how to connect to your KV stores, and demonstrate a few example commands you can use to get started and understand how Redis commands map to the KV SDK.
- For a reference of unsupported Redis commands, see our Redis Compatibility docs
- For a reference of all valid Redis commands, see the official Redis docs
- For a reference of all valid Redis data types, see the official Redis docs
There are two ways to connect to your KV stores:
- The
kv
client, which is a pooled client that uses yourKV_REST_API_TOKEN
andKV_REST_API_URL
to connect to a KV store - The
createClient
method
The createClient
method allows you to use a custom database URL and access token to connect to a Vercel KV database. It takes a config object with the following properties:
Parameters | Required | Type | Description |
---|---|---|---|
url | Yes | string | The REST_API_URL generated when you connect your KV store to a Vercel project |
token | Yes | string | The REST_API_TOKEN generated when you connect your KV store to a Vercel project |
import { createClient } from '@vercel/kv';
export async function GET() {
const users = createClient({
url: process.env.USERS_REST_API_URL,
token: process.env.USERS_REST_API_TOKEN,
});
const user = await users.hgetall('user:me');
const products = createClient({
url: process.env.PRODUCTS_REST_API_URL,
token: process.env.PRODUCTS_REST_API_TOKEN,
});
const product = await products.hgetall('product:shirt');
return Response.json(
{
user,
product,
},
{
status: 200,
},
);
}
The following commands allow you to interact with key values in your Vercel KV database.
Review all the string (key value) commands.
To run the Redis SET
command to create a key, use the .set()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the key |
value | Yes | string, number, object, or boolean | The value to set |
options | No | object | An object whose keys can be command arguments |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.set('setExample', '123abc', { ex: 100, nx: true });
} catch (error) {
// Handle errors
}
}
To run the Redis GET
command to fetch a key's value, use the .get()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the key |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
const getExample = await kv.get('getExample');
console.log(getExample);
} catch (error) {
// Handle errors
}
}
Hashes are like JavaScript objects, allowing you to store multiple values. They're typically used for session caches. The following commands allow you to interact with hash values in your Vercel KV database.
To run the Redis HSET
command to create a hash, use the .hset()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the key |
value | Yes | object | The object value |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.hset('userSession', { userId: 123, email: 'ex@example.com' });
} catch (error) {
// Handle errors
}
}
To run the Redis HGET
command to fetch a key's value from a hash, use the .hget()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the hash |
field | Yes | string | The name of the key to fetch from the hash |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
const userId = await kv.hget('userSession', 'userId');
console.log(userId);
} catch (error) {
// Handle errors
}
}
Lists are linked lists of string values. They're typically used for queue management in background worker systems. The following commands allow you to interact with hash values in your Vercel KV database.
To run the Redis LPUSH
command to create a list or append an item to an existing one, use the .lpush()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the list |
ele1 , ele2 | Yes | list of the same type | You can pass as many parameters as you want of the same type. They will be the elements of the list. |
options | No | object | An object whose keys can be command arguments |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.lpush(
'badIpList',
'abc12304040',
'xyz98773456',
'you can keep going',
"as long as they're",
'all the same type',
);
} catch (error) {
// Handle errors
}
}
To run the Redis LRANGE
command to fetch values from a list, use the .lrange()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the list |
start | Yes | number | The beginning index in the range of items to return from the list. 0 is the first element. |
end | Yes | number | The final index in the range of items to return from the list. 0 is the first element. |
The start and end indexes can be negative numbers. -1
is the end of the list.
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
// 0 is the first element; -1 is the last element
// So this returns the whole list
const list = await kv.lrange('badIpList', 0, -1);
console.log(userId);
} catch (error) {
// Handle errors
}
}
Sets are unordered collections of unique string values. They're typically used for tracking unique items and representing relations. The following commands allow you to interact with sets in your Vercel KV database.
To run the Redis SADD
command to add specified members to the set stored at the specified key, use the .sadd()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the set |
mem1 , mem2 | Yes | list of strings | You can pass as many members as you want. They will be the members of the list. |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.sadd('myset', 'mem1', 'mem2');
} catch (error) {
// Handle errors
}
}
To run the Redis SREM
command to remove the specified members from the set stored at the specified key, use the .srem()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the set |
mem1 , mem2 | Yes | list of strings | You can pass as many members as you want. They will be the members of the list. |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.srem('myset', 'mem1', 'mem2');
} catch (error) {
// Handle errors
}
}
To run the Redis SISMEMBER
command to check if the specified member is a member of the set stored at the specified key, use the .sismember()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the set |
member | Yes | string | The member that you want to check for |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
const isMember = await kv.sismember('myset', 'member');
// returns 1 if the member is part of the set and 0 if not
console.log(isMember);
} catch (error) {
// Handle errors
}
}
Sorted sets are collections of unique string values (members) ordered by an associated score. They're typically used for maintaining ordered lists such as high scores. The following commands allow you to interact with sets in your Vercel KV database.
Review all the sorted set commands.
To run the Redis ZADD
command to add all the specified members with the specified scores to the sorted set stored at the specified key, use the .zadd()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the set |
{score: 1, member: 'mem1'} , {score: 2, member: 'mem2'} | Yes | list of score objects: | You can pass as many score-member objects as you want. They will be the members of the list ordered by the score of each object. |
options | No | object | An object whose keys can be command arguments |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.zadd(
'mysortedset',
{ score: 1, member: 'team1' },
{ score: 2, member: 'team2' },
);
} catch (error) {
// Handle errors
}
}
To run the Redis ZRANGE
command to get the specified member(s) within a specified range of scores in the sorted set stored at the specified key, use the .zrange()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the set |
start | Yes | number | The start score of the range |
stop | Yes | number | The end score of the range |
options | No | object | An object whose keys can be command arguments |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
const data = await kv.zrange('mysortedset', 1, 3);
console.log(data);
} catch (error) {
// Handle errors
}
}
Bitmaps are an extension of the string data type with the ability of containing bit vectors. They're typically used for efficient set representations where the members correspond to integers 0-N
or for object permissions. The following commands allow you to interact with sets in your Vercel KV database.
Review all the bitmap commands.
To run the Redis SETBIT
command to set or clear the bit at the specified offset in the string value stored at the specified key, use the .setbit()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the string value |
offset | Yes | number | The offset of the bit to be set or cleared |
value | Yes | number | Whether to set or clear the bit: 1 to set and 0 to clear |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
await kv.setbit('mybitmap', 7, 1);
} catch (error) {
// Handle errors
}
}
To run the Redis GETBIT
command to get the bit value at the specified offset in the string value stored at the specified key, use the .getbit()
method, with the following parameters:
Parameters | Required | Type | Description |
---|---|---|---|
key | Yes | string | The name of the string value |
offset | Yes | number | The offset of the bit to be retrieved |
import { kv } from '@vercel/kv';
async function exampleCommands() {
try {
const bitvalue = await kv.setbit('mybitmap', 7);
console.log(bitvalue);
} catch (error) {
// Handle errors
}
}
Was this helpful?