storage icon indicating copy to clipboard operation
storage copied to clipboard

Purely numeric string comparisons will get false

Open moondie opened this issue 3 years ago • 2 comments

I compare the password entered by the user (which I'm sure is of type string) with the password obtained by querying KV, if the password is a normal string, the comparison result is normal, while if the password is a plain number, then the comparison result will be false.

my code:

interface userdata {
  [key: string]: unknown;
  password: string;
  balance: number;
}
 const fields = ["password", "balance"];
  const getdata = await kv.hmget<userdata>(username, ...fields);
if (!getdata || getdata?.password !== password) {  // will be false
    response = NextResponse.json(
      {
        error: true,
        msg: "username or password error",
      },
      {
        status: 401,
      },
    );
  }```

moondie avatar Sep 04 '23 02:09 moondie

Even with the declaration "

interface userdata {
  [key: string]: unknown;
  password: string;
  balance: number;
}

" , the type of getdata?.password is still Number.

moondie avatar Sep 04 '23 02:09 moondie

Hi @moondie. The default kv client has automaticDeserialization set to true which means it will try to deserialize all string values it receives. In this case it sees a number string and deserializes it a number. I can see how this can be confusing but it is expected behaviour. You can disable automaticDeserialization like so:

import { kv, createClient } from '@vercel/kv';

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

await customKvClient.set('password', 1);

console.log(await kv.get('password')); // 1
console.log(await customKvClient.get('password')); // '1'

You can read more about automaticDeserilaization on the README.

adriancooney avatar Sep 05 '23 11:09 adriancooney