How do I access KV values in react app


Probaly a basic question but I am going in loop with this on so appreciate if anyone can help.

For my React App. I have a KV set-up and binding declared in the functions tab. I want to access this value but if the react build fails with various scenarios -

  1. I tried using env.KVName but that fails because env is not defined and npm build fails
  2. I tried adding functions folder with a onRequest function but while the deployment is succesful and it shows up in the functions route, the fetch from the display page isn’t working and I get an internal server error on the log.

Is there a simple tutorial available to fetch KV from a react app? I’ve already built a simple worker where this get works fine using env but it is for React that I can’t find anything that would tell me what is the right way to fetch and use KV.

You can not access KV variables easily during npm build. They are only avaiable during run.

1 Like

Thanks, at runtime is fine, how do I do that? Is there a guide/Git I can look at for example?

Can you share your code using onRequest and KV part.

`const getData = async () => {

const response = await fetch('/BSE_DATA');
if (!response.ok) {
  const message = `An error has occured: ${response.status}`;
  throw new Error(message);
output = await response.json();

There is a route Called /BSE_DATA in the functions tab generated as part of the CF deployment

& From functions file

export async function onRequest({ context }) {
// Contents of context object
const {
request, // same as existing Worker API
env, // same as existing Worker API
params, // if filename includes [id] or [[path]]
waitUntil, // same as ctx.waitUntil in existing Worker API
next, // used for middleware or to fetch assets
data, // arbitrary space for passing data between middlewares
} = context;

let fdData = "Hello, world!"; 
fdData = await context.env.BSE_DATA.get("FD_DATA");
return new Response(fdData);



You can probably change fdData = await context.env.BSE_DATA.get("FD_DATA"); to fdData = await env.BSE_DATA.get("FD_DATA");. What error are you getting? Does it not find a value? If you are using pages then you need to define a local KV store as, unlike workers, it doesn’t use the remote KV stores.

Currently I get an error 500 in the first Fectch function call, which is strange considering the redirection exists in the deployed application. I can see the binding and route in the deployed config on CL dashboard.

I can change it to env, by changing the env as function input paran but that won’t fix current issue.

I managed to get this working, by using the complete URL and request headers as the second parameter to the fetch.