[▲ Vercel Community](/) · [Categories](/categories) · [Latest](/latest) · [Top](/top) · [Live](/live)

[Help](/c/help/9)

# Null returned from KV database

47 views · 0 likes · 2 posts


Jblayter (@jblayter) · 2024-07-20

I am trying to add in the KV Storage into the server side API code to help performance. I found that I am successful at setting the value in the KV store but retrieving it always returns a null value.

Import Line
```
import { kv } from '@vercel/kv';
```

Function
```
// Get sport_id by sport key
export async function getSportID(sport_key: string): Promise<number> {
  try {
    const startTime = Date.now();
    const cacheKey = `sport_${sport_key}`;
    console.log("cacheKey", cacheKey);
    if (await kv.exists(cacheKey)) {
      const cachedSport = await kv.get(cacheKey);
      console.log("cachedSport", cachedSport);
      if (cachedSport) {
        console.log("Returned from cache");
        return cachedSport as unknown as number;
      }
    }
    console.log("Returned from db");
    const pool = await initializePool();
    const sport = await pool.any(
      sql.unsafe`
        SELECT
          sport_id
        FROM
          sport
        WHERE
          key = ${sport_key}
        `
    );
    const sport_id = sport?.[0]?.sport_id;
    console.log("sport_id", sport_id);
    const setSportResult = await kv.set(cacheKey,sport_id);
    console.log("setSportResult", setSportResult);
    const endTime = Date.now();
    console.log("Time taken to get sport_id", endTime - startTime);
    return sport_id;
  } catch (error) {
    console.error('Failed to fetch sport:', error);
    throw new Error('Unable to retrieve sport');
  }
}
```

Console output when I run it. 
```
cacheKey sport_basketball_wnba
cachedSport null
Returned from db
sport_id 15
setSportResult OK
Time taken to get sport_id 1243
```

When I run the CLI in the browser it also works
```
GET sport_basketball_wnba
15
```


Pauline P. Narvas (@pawlean) · 2024-07-24

Hi @jblayter!

Just following up here as it's been a few days - did you manage to solve this?

I'll also cross-post some documentation that may be helpful:
https://vercel.com/docs/storage/vercel-kv