javascriptcloudflarecloudflare-workerswranglercloudflare-kv

How to user KV in cloudflare workers?


I am using wrangler v3.78. I am trying to make a test worker, just to figure out how KV database works. This is my code:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const { pathname } = new URL(request.url)

  if (request.method === 'GET' && pathname === '/retrieve') {
    const key = 'data'
    const data = await env.BINDING_NAME.get(key, 'text')
    return new Response(data || 'Key not found', { status: 200 })
  } else if (request.method === 'POST' && pathname === '/store') {
    const data = await request.text()
    await env.BINDING_NAME.put('data', data)
    return new Response('Data stored successfully', { status: 200 })
  } else {
    return new Response(JSON.stringify({ error: 404, message: 'Not found' }), {
      status: 404,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}

when I run wrangler dev or npm run dev I get these errors:

X [ERROR] service core:user:api: Uncaught Error: Dynamic require of "node:stream" is not supported

    at null.<anonymous> (core:user:api:9:11)
    at null.<anonymous> (core:user:api:107:28)
    at null.<anonymous> (core:user:api:1222:3)


X [ERROR] MiniflareCoreError [ERR_RUNTIME_FAILURE]: The Workers runtime failed to start. There is likely additional logging output above.

Any assistance in what I am doing wrong to get these errors and how to fix them would be very appreciated, thanks. I am very new to any backend developing, and tbh I don't really understand what some of the code even does, so there is a good chance I am getting it all wrong. Thanks anyway


Solution

  • One of the issues here could be related to the old syntax. Cloudflare recommend replace addEventListener('fetch', ...) to the async fetch, as described here.

    Also, tha main thread in the GitHub about that: https://github.com/cloudflare/workerd/issues/854

    Fixed version should looks something like this (unfortunately I don't have ability to test it):

    export default {
      async fetch(request, env) {
        const { pathname } = new URL(request.url);
    
        if (request.method === 'GET' && pathname === '/retrieve') {
          const key = 'data';
          const data = await env.BINDING_NAME.get(key, 'text');
          return new Response(data || 'Key not found', { status: 200 });
        } else if (request.method === 'POST' && pathname === '/store') {
          const data = await request.text();
          await env.BINDING_NAME.put('data', data);
          return new Response('Data stored successfully', { status: 200 });
        } else {
          return new Response(JSON.stringify({ error: 404, message: 'Not found' }), {
            status: 404,
            headers: { 'Content-Type': 'application/json' },
          });
        }
      }
    };