https://discord.cloudflare.com logo
Join Discord
Powered by
# workers-help
  • Incorrect type for Promise: the Promise did not resolve to 'Response'.
    m

    mattp

    04/14/2023, 8:49 AM
    I'm using the
    itty-router
    for routing
    Copy code
    typescript
    export default {
      fetch: async (request: Request, env: Env, context: Context) => {
        context.slack = new Slack(env.SLACK_APP_BOT_TOKEN);
        context.waitUntil(router.handle(request, env, context));
      },
    };
    k
    • 2
    • 2
  • Problem with multiple Workers bound to Workers Routes
    d

    duplex

    04/14/2023, 11:46 AM
    I have a following routes table: 1.
    api.example.com/path-a/*
    ->
    worker-a
    2.
    api.example.com/path-b/*
    ->
    worker-b
    3.
    api.example.com/path-c*
    ->
    worker-c
    Every worker has a following setting in `worker.toml`:
    Copy code
    [env.production]
    name = "worker-a"
    route = { pattern = "api.example.com/path-a/*", zone_name = "example.com" }
    I fail to access these workers over HTTP. Looks like I'm missing something, help me out
    s
    • 2
    • 16
  • Cannot fetch service binding as it gets "canceled"
    d

    duplex

    04/14/2023, 1:06 PM
    My worker wrangler TOML file has following settings:
    Copy code
    [[env.production.services]]
    binding = "workerA"
    service = "worker-a"
    
    [[env.production.services]]
    binding = "workerB"
    service = "worker-b"
    Both services are called like that:
    Copy code
    const workerAResponse = await env.workerA.fetch(
      new Request(new URL(`worker-a/${id}`, env.WORKER_A_DOMAIN)),
      {
        headers: request.clone().headers,
      }
    );
    
    
    if (!workerAResponse.ok) { return workerAResponse }
    
    const { public_id } = await workerAResponse.json();
    
    const workerBResponse = await env.workerB.fetch(
      new Request(new URL(`worker-b/${public_id}`, env.WORKER_B_DOMAIN)),
      {
        headers: request.clone().headers,
      }
    );
    
    if (!workerBResponse.ok) { return workerBResponse; }
    Request to
    worker-a
    is successful, however a request to` worker-b` is canceled, as
    wrangler tail
    says:
    GET <some-url> - Canceled @ 4/14/2023, 5:03:23 PM
    What can possibly go wrong about it? And why worker-b response is canceled whereas worker-a (both are set up literally the same) works just fine. By the way, worker responds with
    200
    , but due to the
    outcome: "canceled"
    it is not taken into account ;/
    k
    • 2
    • 12
  • workers generated from Terraform have a "dev" route that cannot be managed by tf
    g

    glynn

    04/14/2023, 3:17 PM
    We are kicking the tyres of the Cloudflare ecosystem. We're using Terraform to stand up some infrastructure: - a KV store - a number of workers that have the KV store bound to them We can successfully deploy the workers but they come with a automatically created route that is not under the control of Terraform e.g.
    delete_todo_dev.somedomain.workers.dev    somedomain.workers.dev
    This route is disabled by default and can only be enabled in the UI. We are trying to enable the routes in Terraform so that we output the route's URL but as we didn't create the route, we can't interact with it. How is a Terraform project meant to create and manage routes programmatically? If we use the Wrangler tool, then the route gets enabled on creation but using Terraform it doesn't. We'd rather use Terraform than use Wrangler in a shell script, for obvious reasons. Any best practice advise is very welcome.
    k
    • 2
    • 2
  • Networking question r.e. using one or two workers for the API and image uploads?
    n

    nora

    04/14/2023, 8:44 PM
    If I were to accept image uploads through a service, which then itself uploads the image to Cloudflare Images, would it be more suitable to do this through a second worker service, outside of my main API, or would it not matter in terms of networking?
    • 1
    • 1
  • typescript error when explicitly importing types
    j

    jeffo

    04/15/2023, 1:30 AM
    i'm writing a worker / pages function and am getting a typescript error when i explicitly import a type into my .ts file. this code works fine and shows now errors:
    Copy code
    export const onRequest: PagesFunction = async (context) => {
      return new Response( 'foobar' )
    }
    while this code causes a typescript error:
    Copy code
    import type {
      PagesFunction,
    } from '@cloudflare/workers-types/experimental'
    
    export const onRequest: PagesFunction = async (context) => {
      return new Response( 'foobar' )
    }
    the error i'm getting is:
    Copy code
    Type '(context: EventContext<unknown, any, Record<string, unknown>>) => Promise<Response>' is not assignable to type 'PagesFunction'.
      Type 'Promise<Response>' is not assignable to type 'Response | Promise<Response>'.
        Type 'Promise<Response>' is not assignable to type 'Promise<import(".../node_modules/@cloudflare/workers-types/experimental/index").Response>'.
          Type 'Response' is missing the following properties from type 'Response': webSocket, cf
    i tried to ignore the error and delete the
    import type
    bits, but it's nagging at me and i can't let it go. 🙂 any thoughts or advice? has anyone else run into the same problem?
    s
    • 2
    • 4
  • crosspost: access remote KV namespace during local development?
    j

    jeffo

    04/15/2023, 9:39 PM
    i wasn't sure if i should post this in pages-help or workers-help since it pertains to KV binding for local pages dev environments, so i'm just posting a link to the post i created over in pages-help: https://discord.com/channels/595317990191398933/1096910816999112714 this has been driving me mad the past 24+ hours, so any tips, pointers, or insights are appreciated! 🙂
  • OAuth token refresh
    j

    Jori

    04/17/2023, 9:32 AM
    I'm trying to create an integration with our CRM, however the application doesn't allow generating a set api key I can continue using, it requires users to log in using OAuth2. I'm using the service to process incoming orders sent to a webhook, and automatically enter them into the system. This means there's a highly irregular and unpredictable input. My question is, how do I keep refreshing the token, to make sure it doesn't expire (and require user interaction)?
    z
    • 2
    • 17
  • How to cache streams?
    k

    Kartik

    04/17/2023, 1:19 PM
    app.get("/download", async (ctx) => { const address = ctx.req.query("address"); try { if (address) { const url = new URL(decodeURIComponent(address)); url.protocol = "https"; const { readable, writable } = new TransformStream(); url.protocol = "https"; const result = await fetch(url, { headers: { ...ctx.req.headers, redirect: "follow", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36", }, }); let contentLength = result.headers.get("Content-Length"); let response = new Response(result.body); response.headers.append("Cache-Control", "no-cache"); response.headers.append("content-type", "audio/mpeg"); if (contentLength) { response.headers.append("Content-Length", contentLength); } response.body?.pipeTo(writable); return new Response(readable, response); } return ctx.newResponse("Not Found", 404); } catch (error) { console.log(error); return ctx.newResponse("Internal Server Error", 500); } }); I have this script that i can use to proxy a audio file from a url, how can i cache this audio file in cache? so i don't have to ping the server?
    k
    • 2
    • 8
  • Workers CPU Time and Crypto question
    j

    Joyte

    04/18/2023, 3:46 AM
    Hi. I'm using workers with the WebCrypto API for hashing, encryption and token auth. My main concern is though, is how slow PBKDF2 is. Should I be concerned about this? I'm currently hitting around ~20ms on average, with SHA-512 and 100k iterations. That does vary a bit though, and the main point of the worker is to hold encrypted content, of which could be 50mb in size or more for each individual thing.
    z
    i
    • 3
    • 27
  • pages uploading fail
    c

    coolvibesreloaded

    04/18/2023, 1:57 PM
    bsically i'v brought a domain on cloudflare called cvrsocial.uk so i'v uploaded and deployed so i'm getting error could someone please elaborate on this also on that domain its giving me host error?
    w
    • 2
    • 11
  • Disabling automatic asset caching
    m

    mercmoods

    04/18/2023, 2:30 PM
    I’m seeing some very confusing cache-api behaviour on a worker of mine. I’ve set cache-control headers on a .css asset to be max-age=0, no-cache, but the worker is still caching the request. I can see this because the age response header is a non-zero value and the cf-cache-status says HIT. Is there any way I can turn off this automatic asset caching/any info of what’s going on under the hood?
    s
    • 2
    • 6
  • DNS problems
    a

    aye

    04/18/2023, 5:39 PM
    Hello, I bought a domain name yesterday and a VPS on the same website : 1984.hosting, but I started to setup my domain with cloudflare, the nameservers has been updated, but when I go on my domain, it give me 1984.hosting, here is a screen of my DNS : ( sorry for the tags, idk what to put, i'm new on this server )
    v
    • 2
    • 1
  • POST request inside a worker (not working)
    s

    Skye

    04/18/2023, 6:17 PM
    That's definitely doable, yes
    • 1
    • 7
  • An worker sample: "Alter headers" doesn't work with root domain.
    n

    naosk8

    04/19/2023, 6:26 AM
    Hello, I'm a learner of Cloudflare Worker 🙂 I faced some problems in a tutorial, so kindly help me. Thank you in advance. Detailed steps of my attempts are written below. MY GOAL: To connect my GoogleAnalytics and Clarity tags to my website. My site is hosted on root domain. (i.e. https://example.com) WHAT I UNDERSTOOD: Read some articles and found that it's better for my case to use Route matching (not Custom domain) because I just want to modify the html a little bit and want to apply it to an existing domain. NOW I'M TRYING: 1. Use a Worker like a proxy to modify HTML itself. (inject some script tags) → it didn't work. (details are in this post: https://community.cloudflare.com/t/cannot-trigger-worker-under-my-routing-googleanalytics-and-clarity-tags-with-htmlrewriter/498763?u=iam.nao.ito) 2. So, back to the basic. I tried to follow a tutorial: https://developers.cloudflare.com/workers/examples/alter-headers/ to review the basic rule. 3. Create a worker by following the tutorial 1. Create a new service worker on Cloudflare UI (dashboard) 2. Copy and paste the tutorial code in the
    Quick edit
    section of the worker. 3. Confirm that the header has changed on the preview panel. 4. Save and deploy 5. Create a new Route settings for the worker (pattern: example.com/, zone: example.com) 6. access to
    https://example.com
    → The page is of course available like before, but the header is not changed like what was in the preview window (step 3-3). Also, the number of request didn't increase (it seems that my access is not routed to the worker). Is there any step I missed? Or, anyone faced / solved the same problem? Thank you.
  • host error
    c

    coolvibesreloaded

    04/19/2023, 4:07 PM
    can someone please pleaasae help i'm now worrying i want this worpress up and running my site is now showing i have DNS records correct as well can some please help
    w
    • 2
    • 3
  • Using NPM packages in Workers
    t

    ThatsTasty

    04/19/2023, 7:20 PM
    My understanding is that Wrangler will use esbuild to bundle any NPM packages upon deploy. I was trying to use just one package (probe-image-size) and can't get this to happen. I was developing locally and got errors then I tried the command to do a dry run locally and when I did so it still didn't bundle it... Is it possible to use NPM packages? What am I missing? Thank you!
    k
    • 2
    • 5
  • Chat App (using workers & web socket) Tutorial?
    r

    rattlesnake

    04/20/2023, 4:50 AM
    Hi all. Is there any simple tutorial that shows how to build a chat app by using various CF services (e.g., Workers, KV, R2, etc) ? I found a chat app deployment tutorial but it's not that useful as it only contains front-end code. Thank you, Cloudflare. Your products are amazing! If only there were more docs available.
    v
    • 2
    • 3
  • Worker Service Binding ReadableStream is disturbed
    t

    Tino

    04/20/2023, 12:59 PM
    Hello, I am using two workers where one is working as a gateway to validate authentication and does a request to itself as a fallthrough (cf handlers first request, internal request goes to DNS origin) lets call this worker A Calling this worker via service binding from worker B results in a 200 response (using logging i can see that both the worker got the request with a 200 and the origin server logging results a 200) But this result is unreadable since its telling me the following: "This ReadableStream is disturbed (has already been read from), and cannot be used as a body." when i try to read the body. When doing a request from the browser to Worker A everything is working as expected. Path: Worker B -> Worker A -> Worker A (internal dns to kubernetes cluster in azure) I am wondering why the request is unreadable, is this a bug ? i expected the JSON result in the response but all i can see is the status code 200 and eveything else seems empty.
    • 1
    • 1
  • Workers, Pages Functions & 10ms CPU Time
    t

    TigersWay

    04/21/2023, 12:26 AM
    Hi, Studying what could fit in the well-known "10ms CPU Time", I was surprised by some "discrepancies": - the same code in a worker is going to be (statistically) slightly faster than in a page-function, - that same function - if the only one - is going to be (statistically) slightly faster than grouped with others even non used. Of course, it's never much, but enough to make it jump over the 10ms! Is that logical, even expected? Anyone has done some real extensive tests?
    z
    s
    • 3
    • 16
  • Cannot read properties of undefined (reading 'fetch')
    m

    marcoow

    04/21/2023, 10:45 AM
    I'm trying to write a worker in Rust with the worker crate. I'm using the fetch API via the service worker global scope:
    Copy code
    async fn request_sendgrid(api_key: &str, data: String) -> Result<u16, NetworkError> {
        let mut opts = RequestInit::new();
        opts.method("POST");
        opts.mode(RequestMode::Cors);
        opts.body(Some(&JsValue::from_str(&data)));
    
        let request = FetchRequest::new_with_str_and_init(&"https://api.sendgrid.com/v3/mail/send", &opts)?;
    
        request
            .headers()
            .set("Authorization", &format!("Bearer {}", api_key))?;
        request.headers().set("Content-Type", "application/json")?;
    
        let worker_global_scope = js_sys::global().dyn_into::<web_sys::ServiceWorkerGlobalScope>()?;
        let resp_value = JsFuture::from(worker_global_scope.fetch_with_request(&request)).await?;
        assert!(resp_value.is_instance_of::<FetchResponse>());
        let response: FetchResponse = resp_value.dyn_into()?;
    
        Ok(response.status())
    }
    The problem now is when running this, fetching the WASM fails with the above error at `build/worker/shim.mjs:181:20`:
    Copy code
    function fetch(req, env, ctx) {
      const ret = wasm.fetch(addHeapObject(req), addHeapObject(env), addHeapObject(ctx));
      return takeObject(ret);
    }
    k
    • 2
    • 2
  • Worker Metrics using gql api endpoint
    t

    tabletoe

    04/21/2023, 2:59 PM
    I'm trying to create a custom dashboard for my worker. Looking at the sum fields in the documentation I can't find what the units of the responses are. Can anyone assist? E.g. what is the unit for
    wallTime
    here?
    k
    • 2
    • 5
  • upload email body to r2
    f

    ForwardMotion

    04/21/2023, 5:11 PM
    working on getting a email worker to put a received email into a r2 bucket so far it works sorta. it creates the object but it empty. if i used
    message.headers.get('from')
    as the object it puts it in the r2 bucket as expected with the content being the sender, but if i use
    message.headers.get('body')
    it fails as if the object was empty. question is what are the email headers and am i right to think that 'body' is not one of them. i can't seem to find the doc with all the possible headers. if body isn't the header for the email content is there one?
    k
    h
    • 3
    • 12
  • Example AllowList issues
    w

    woulduno

    04/22/2023, 3:02 AM
    Good day, using the example for allow list, the email trigger test will work properly. Yet sending an email to that route results in the reject message. I have validated the email address several times. Is there something trivial I am missing here? I did alter the reject message to make sure it was the worker sending the bounce.
    c
    • 2
    • 11
  • Creating Workers API?
    j

    jwithing

    04/23/2023, 3:14 AM
    Is there an API to create a worker? I wasn’t able to find it in the documentation. Specifically, I’m setting up a form to create redirects. * User visits my site and submits a form. * The values of the form’s input field are used in the creation of a new worker. * I would then attach this new worker to a route on my domain. I see the Worker Route API, but I don’t see a “create new worker” API. Am I missing something?
    h
    s
    +2
    • 5
    • 40
  • Host Error
    u

    樱花美子

    04/23/2023, 1:46 PM

    https://www.pb2legacy.me:8443/assets/00b1287a89ec490d9bbb09011465a1c5.png▾

    Https connection does not work properly, due unrecognized certificate.
    • 1
    • 1
  • Cloudflare workers + pages, possible KV, R2 and D1, do i need a service discovery thing?
    a

    anteac

    04/24/2023, 3:59 AM
    anteac: I've read up all the docs but im not sure if those things provide a near kubernetes like cloud worker restarts or wehatever it needs to do to keep going, serverless., or microservices. idk what my usecase even is, serverless or microservices? Plan is running nextjs website and seperate API server on edgerouter mode on CF workers, coupled with some postgres supported DB and lastly a graphql server that a discord.js based bot consumes. theorectly possible all on cloudflare workers/pages, but I assumed you had to have some software to keep an eye on all the services to provide redundancy and selfhealing if needeed like kube. Like what am i missing here? Whats the best setup if I were to put everything in CF workers/pages? Do I even need a service discovery type thing, or do i need like a API gateway a lá Kong or something like these things https://github.com/envoyproxy/envoy or https://github.com/istio/istio or https://github.com/solo-io/gloo? anyone have experience with organizing something very similar recently? and if i need any of those api gateways?. I assume terraform would do the trick but I cant find any info on that combinened with edge workers only ,,,
    s
    • 2
    • 8
  • env.dispatcher type?
    x

    xorlop

    04/24/2023, 1:12 PM
    I am struggling with ascertaining the type of
    env
    ,
    env.dispatcher
    , and the result of
    env.dispatcher.get(someString)
    . Can anyone point me in the right direction? I was not able to find anything in
    @cloudflare/worker-types/index.d.ts
    .... Also for
    env
    itself, I kind of just type it like this:
    Copy code
    type Env {
      dispatcher: any;
    }
    The relevant documentation: https://developers.cloudflare.com/cloudflare-for-platforms/workers-for-platforms/ It does not contain any TS 😦 Quick search on GH returns this: https://github.com/drivly/platform.workers.cf/blob/8fbdd76549b58414528611f75a04065fb1f49b12/src/env.ts#L9 Is that the recommended way to type this?
    k
    • 2
    • 2
  • New request headers?
    f

    firefall

    04/24/2023, 5:51 PM
    Did Cloudflare change request headers being sent from a worker while using fetch? Seems like my workers started to get CORS issues after the weekend all of a sudden.
    s
    c
    • 3
    • 10
  • There's some issue with logs from CF workers running on the mainland China network
    r

    ranrub

    04/24/2023, 9:03 PM
    Any explanation as to why workers logs don't work there and when this issue should be resolved? Thanks!
    w
    t
    • 3
    • 4
12345...10Latest