Reference

Vercel KV Rest API

Learn how to access and use your KV database with the Vercel KV Rest API.
Table of Contents

Vercel KV is available on Hobby and Pro plans

You can send Redis commands to Vercel KV in the following ways:

You should only use Vercel KV API if you're using a runtime that does not have a Redis client, or does not support Node.js or Edge.

To get started using Vercel KV API, you need your database's REST API URL and REST API token, which Vercel generates when you connect your project. You'll find your URL and token in your project's dashboard under the following environment variables:

  • KV_REST_API_URL
  • KV_REST_API_TOKEN

To access them locally run the following command at the root directory of your project, using Vercel CLI:

vercel env pull .env.development.local

You can then use the environment variables in your code with process.env:

basic-request-example.ts
fetch(`${process.env.KV_REST_API_URL}`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Or with the _token query parameter to authenticate your requests.

token-param-example.ts
const { KV_REST_API_URL, KV_REST_API_TOKEN } = process.env;
 
fetch(`${KV_REST_API_URL}?_token=${KV_REST_API_TOKEN}`)
  .then((response) => response.json())
  .then((data) => console.log(data));

Vercel automatically generates an API URL when you connect your KV database to a project, which you can find under Endpoint on your database information page.

To make requests to your API URL, pass the API token in the Authorization header using the code from the Fetch tab of the dashboard quickstart:

Vercel KV also generates a read-only API token, which grants access only to read commands. It also disables the KEYS command. You can access your read-only token with the KV_REST_API_READ_ONLY_TOKEN environment variable.

You can send basic commands in two ways:

  • Add commands to the path of your API URL, separating each element of the command into their own paths with a /.
    • If a value contains slashes, such as setting a key named redirectURL to https://example.com, you must send commands in the body.
  • Send Redis commands in the body of a POST request to your KV API URL. You must break each parameter of the command out into items in an array. Commands can have as many parameters as is allowed by the Redis Protocol.

[path]/set/{key}/{value}/{options}

Example

Define in path:

define-in-path-example.ts
// SET userId abc EX 100
fetch(`${process.env.KV_REST_API_URL}/set/userId/abc/ex/100`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Define in body:

request-body-example.ts
fetch(`${process.env.KV_REST_API_URL}/`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
  body: '["HSET", "sessionData", "username", "exampleUser123"]',
  method: 'POST',
})
  .then((response) => response.json())
  .then((data) => console.log(data));
ParametersRequiredTypeDescription
keyYes

string

The name of the key
valueYes

string, number or boolean

The value to set
optionsNo

object

An object whose keys can be command arguments

[path]/get/{key}

Example

Define in path:

define-in-path-example.ts
fetch(`${process.env.KV_REST_API_URL}/get/userId`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Define in body:

request-body-example.ts
fetch(`${process.env.KV_REST_API_URL}/`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
  body: '["GET", "userId"]',
  method: 'POST',
})
  .then((response) => response.json())
  .then((data) => console.log(data));
ParametersRequiredTypeDescription
keyYes

string

The name of the key
  • url = ${process.env.KV_REST_API_URL}/set/{key}
  • method = POST
  • Body = JSON object
example-fetch.ts
// SET userSession jsonObject
fetch(`${process.env.KV_REST_API_URL}/set/userSession`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
  body: JSON.stringify({
    sessid: '12345',
    session_name: 'abcdef',
    user: {
      uid: 31,
      name: 'test_user',
      mail: 'user@example.com',
    },
  }),
  method: 'POST',
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Path Parameters

Path ParametersRequiredTypeDescription
keyYes

string

The name of the key

This allows you to store user file contents in your KV database.

Endpoint:

  • url = ${process.env.KV_REST_API_URL}/set/binaryKey
  • method = POST
  • Body = Binary data, such as files attached through HTML <input> elements

Example

file-input.tsx
export default function FileInput() {
  const fileInputRef = useRef<HTMLInputElement | null>(null);
 
  function setFileToKey() {
    if (!fileInputRef?.current?.files) {
      return console.log('No file found');
    }
    fetch(`${process.env.KV_REST_API_URL}/set/binaryKey`, {
      headers: {
        Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
      },
      body: fileInputRef.current.files[0],
      method: 'POST',
    })
      .then((response) => response.json())
      .then((data) => console.log(data));
  }
 
  return (
    <>
      <input ref={fileInputRef} type="file" />
      <button onClick={setFileToKey}>Upload file</button>
    </>
  );
}

There are two ways to send multiple commands to your KV database from the Rest API:

  • Pipelining - Pipelining executes multiple commands in one network request. However, pipelining is not atomic, so other client requests can be processed in the between.
  • Transactions - Transactions allow you to send multiple commands to your KV database in one network request. However, transactions are executed atomically, which means commands sent from other client instances will not be executed in between a transaction's commands.

Endpoint:

  • url= ${process.env.KV_REST_API_URL}/pipeline
  • method = POST
  • body = Redis commands in a two-dimensional array. Define arguments in the same order that you would with a standard Redis command

Example

pipelining-example.ts
fetch(`${process.env.KV_REST_API_URL}/pipeline`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
  // SET userEmail example@example.com EX 100
  // GET userEmail
  body: `[
    ["SET", "userEmail", "example@example.com", "EX", 100],
    ["GET", "userEmail"]
  ]`,
  method: 'POST',
})
  .then((response) => response.json())
  .then((data) => console.table(data));

Endpoint:

  • url = ${process.env.KV_REST_API_URL}/multi-exec
  • method = POST
  • body = Redis commands in a two-dimensional array. Define arguments in the same order that you would with a standard Redis command

Example

transaction-example.ts
fetch(`${process.env.KV_REST_API_URL}/multi-exec`, {
  headers: {
    Authorization: `Bearer ${process.env.KV_REST_API_TOKEN}`,
  },
  // HSET sessionData userEmail example@example.com
  // HGET sessionData userEmail
  body: `[
    ["HSET", "sessionData", "userEmail", "example@example.com"],
    ["HGET", "sessionData", "userEmail"]
  ]`,
  method: 'POST',
})
  .then((response) => response.json())
  .then((data) => console.table(data));

Response

If your transaction is successful, the response will be an array of result objects in the same order as the commands. The following is an example response array:

Transaction response example
[
  {
    "result": "OK"
  },
  {
    "result": "example@example.com"
  }
]

The following table displays the possible HTTP responses you can receive from API requests, and what they mean.

HTTP CodeHTTP StatusMeaning
200OKThe command was successfully executed.
400Bad RequestThe command was invalid/unsupported, contained a syntax error, or failed to execute.
401UnauthorizedAuthentication failed, likely due to an invalid or missing API token.
405Method Not AllowedAn unsupported HTTP method was used. Only HEAD, GET, POST, and PUT methods are allowed when making API requests.
Last updated on July 22, 2024