Reference

@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.
Table of Contents

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.

There are two ways to connect to your KV stores:

  1. The kv client, which is a pooled client that uses your KV_REST_API_TOKEN and KV_REST_API_URL to connect to a KV store
  2. 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:

ParametersRequiredTypeDescription
urlYes

string

The REST_API_URL generated when you connect your KV store to a Vercel project
tokenYes

string

The REST_API_TOKEN generated when you connect your KV store to a Vercel project
Next.js (/app)
Next.js (/pages)
Other frameworks
app/api/create-client/route.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the key
valueYes

string, number, object, or boolean

The value to set
optionsNo

object

An object whose keys can be command arguments
set-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the key
get-example.ts
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.

Review all the hash commands.

To run the Redis HSET command to create a hash, use the .hset() method, with the following parameters:

ParametersRequiredTypeDescription
keyYes

string

The name of the key
valueYes

object

The object value
hset-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the hash
fieldYes

string

The name of the key to fetch from the hash
hget-example.ts
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.

Review all the list commands.

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:

ParametersRequiredTypeDescription
keyYes

string

The name of the list
ele1, ele2Yes

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.
optionsNo

object

An object whose keys can be command arguments
lpush-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the list
startYes

number

The beginning index in the range of items to return from the list. 0 is the first element.
endYes

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.

lrange-example.ts
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.

Review all the set commands.

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:

ParametersRequiredTypeDescription
keyYes

string

The name of the set
mem1, mem2Yes

list of strings

You can pass as many members as you want. They will be the members of the list.
sadd-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the set
mem1, mem2Yes

list of strings

You can pass as many members as you want. They will be the members of the list.
srem-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the set
memberYes

string

The member that you want to check for
sismember-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the set
{score: 1, member: 'mem1'}, {score: 2, member: 'mem2'}Yes

list of score objects: score: number, member: string

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.
optionsNo

object

An object whose keys can be command arguments
zadd-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the set
startYes

number

The start score of the range
stopYes

number

The end score of the range
optionsNo

object

An object whose keys can be command arguments
zrange-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the string value
offsetYes

number

The offset of the bit to be set or cleared
valueYes

number

Whether to set or clear the bit: 1 to set and 0 to clear
setbit-example.ts
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:

ParametersRequiredTypeDescription
keyYes

string

The name of the string value
offsetYes

number

The offset of the bit to be retrieved
getbit-example.ts
import { kv } from '@vercel/kv';
 
async function exampleCommands() {
  try {
    const bitvalue = await kv.setbit('mybitmap', 7);
    console.log(bitvalue);
  } catch (error) {
    // Handle errors
  }
}
Last updated on October 22, 2024