Vercel KV
by
Jikku Jose
in
jikkujose.in

I just tried Vercel KV for evaluating its DX & speed. To be frank, I am not very impressed. But, I can see it being useful to many.

I have been using WebArray for almost all projects that I hack and I believe it suits my needs pretty well.

Since it wasn’t super intuitive, I am making a note on how to get it working.

Vercel KV is a wrapper around a redis instance. Its not meant for large files, but its pretty useful for low latency read/writes.

It requires one package from vercel: kv. This is my package.json:

{
  "dependencies": {
    "@vercel/kv": "^0.1.1"
  }
}

KV requires some setup to complete the process:

  1. Create DB: https://vercel.com/dashboard/stores
  2. Chose KV
  3. Chose Getting Started (side menu)
  4. Connect to project
  5. Let it setup all the connection variables for this to work

That wires up the DB to the project, now implement a basic serverless function in the project to get started. Following is the code to implement a basic counter.

import kv from "@vercel/kv"

export default async function handler(req, res) {
  // Set CORS headers
  res.setHeader("Access-Control-Allow-Origin", "*")
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, OPTIONS"
  )
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization")
  res.setHeader("Access-Control-Allow-Credentials", "true")

  // Handle preflight requests (OPTIONS method)
  if (req.method === "OPTIONS") {
    res.status(204).end()
    return
  }

  const count = (await kv.get("count")) || 0
  await kv.set("count", count + 1)

  res.status(200).json({ count: count + 1 })
}

Visiting the link, would increment the count by one.