Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.set() is automatically running JSON.parse() on the result without telling you #250

Closed
Gbox4 opened this issue Jun 27, 2023 · 2 comments
Closed

Comments

@Gbox4
Copy link

Gbox4 commented Jun 27, 2023

If you run:

import { kv } from "@vercel/kv";

const a1 = "a"
await kv.set(url, a1)
const b1 = await kv.get(url)
console.log("test 1")
console.log(typeof a1)
console.log(typeof b1)

const a2 = "1"
await kv.set(url, a2)
const b2 = await kv.get(url)
console.log("test 2")
console.log(typeof a2)
console.log(typeof b2)

const a3 = "{}"
await kv.set(url, a3)
const b3 = await kv.get(url)
console.log("test 3")
console.log(typeof a3)
console.log(typeof b3)

you get:

test 1
string
string
test 2
string
number
test 3
string
object

Should they not all return string? Is the auto-parsing is the desired behavior? Where is this documented? I couldn't find it here.

@Gbox4 Gbox4 changed the title .get() is automatically running JSON.parse() on the result without telling you .set() is automatically running JSON.parse() on the result without telling you Jun 27, 2023
@adriancooney
Copy link
Collaborator

adriancooney commented Jun 27, 2023

Hi @Gbox4, thanks for the report. The documentation should be clearer here. Automatic deserialization is enabled for the default client (kv) but if you want to disable it, you can create a separate client with automaticDeserialization: false via the createClient method. That looks like:

import { createClient } from "@vercel/kv";

const customKvClient = createClient({
  url: process.env.KV_REST_API_URL,
  token: process.env.KV_REST_API_TOKEN,
  automaticDeserialization: false,
});

The enables the following:

await kv.set("object1", { hello: "world" });

console.log(await kv.get("object1")); // { hello: 'world' }
console.log(await customKvClient.get("object1")); // '{"hello":"world"}'

await kv.set("object2", "{}");

console.log(await kv.get("object2")); // {}
console.log(await customKvClient.get("object2")); // '{}'

@adriancooney
Copy link
Collaborator

Docs updated. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants