https://discord.cloudflare.com logo
Join Discord
Powered by
# workers-help
  • the other API service blocked ip from cloudflare (fetch issue)
    l

    Lloyd

    02/17/2023, 8:04 PM
    I am writing a workers code that sends http requests to other API servers(third-party) and stores the responses in r2. I used "fetch()" to get api response but it returns 403 error via domain workers request.(~.~.workers.dev) But it works on via clicking test button in workers quick edit. It seem to blocking api request by some conditions at third party API. So I checked each "X-Forwarded-For"(workers ip) header. And the result is below. clicking test button in quick edit = 34.29.117.83 (owned by google) request via domain(~.~.workers.dev) = 2a06:98c0:3600::103 (owned by cloudflare) I think the third-party API server blocked ip owned by cloudflare to block WARP vpn(cloudflare service). Therefore The third-party API server never allow ip owned by cloudflare. So is there way to change workers ip to ip that not owned by cloudflare? (using google owned ip like test request) Or when execute fetch() is there a way of deceiving third party API server? I tried set X-Forwarded-For header but it didn't overwrote. thank you for reading this question😁
    k
    a
    r
    • 4
    • 4
  • how to add www. prefix infront my custom domain
    c

    Chaika

    03/15/2023, 10:25 PM
    Looks like Erisa replied to you with the same thing, but it looks like sellpass.io uses Cloudflare. You will need to add your www subdomain as another custom domain within *sellpass*'s (or whoever your provider is), settings (providing that they allow that).
    • 1
    • 1
  • Microsoft Cognitive Services
    r

    rodbs

    03/16/2023, 4:11 PM
    I've opened an issue with Microsoft to check if MS cognitive services SDK works with Workers. https://github.com/microsoft/cognitive-services-speech-sdk-js/issues/645 They've fixed/remove code that was giving me the
    TypeError: globalThis.XMLHttpRequest is not a constructor
    error. But now it seems the sdk cannot connect to Azure's wss server. I'm not sure why but I've read here that wrangler doesn't work with wss but only with ws. Is that right?
    • 1
    • 1
  • My KV binding is not being set by my wrangler.toml file when deploying to my production environment
    j

    jeremynevans

    03/24/2023, 2:59 AM
    Hello Cloudflare Community! My KV binding is not being set by my wrangler.toml file when deploying to my production environment. It works fine on the staging worker, but when I deploy to the production worker the KV binding is wiped, so I have to add it manually using the dashboard after each deploy (which causes downtime). In my wrangler.toml file, I’m setting kv_namespaces in exactly the same way in [env.production] as I am in [env.staging], and also in the top section of the file (with no environment). I’ve searched through this community and can’t find any posts on this exact topic. Below is my full wrangler.toml, and a screenshot of the dashboard with the message recommending updating my wrangler.toml file to keep your local development environment in sync (which I have done). Thanks very much in advance for your help!
    Copy code
    name = "renderer"
    account_id = "16875cc7c5ec0ad968518988c731fcab"
    workers_dev = false
    compatibility_date = "2022-01-20"
    main = "src/api/index.ts"
    
    [vars]
    ENVIRONMENT = "production"
    
    [build]
    command = "npm run build-worker"
    
    kv_namespaces = [
    { binding = "FLOWS_KV", id = "00ca5df4edfa475e82a209d3de5e6d19", preview_id = "00ca5df4edfa475e82a209d3de5e6d19" }
    ]
    
    [env.production]
    vars = { ENVIRONMENT = "production" }
    workers_dev = true
    kv_namespaces = [
    { binding = "FLOWS_KV", id = "00ca5df4edfa475e82a209d3de5e6d19", preview_id = "00ca5df4edfa475e82a209d3de5e6d19" }
    ]
    
    [env.staging]
    vars = { ENVIRONMENT = "staging" }
    kv_namespaces = [
    { binding = "FLOWS_KV", id = "00ca5df4edfa475e82a209d3de5e6d19", preview_id = "00ca5df4edfa475e82a209d3de5e6d19" }
    ]
    s
    • 2
    • 5
  • How to create a html.
    a

    Allright

    03/30/2023, 3:29 AM
    I have a html page which like does url shortening, I want to use it on cloudflare workers so where is like the file creation icon. Like how do I create a index.html & other files?
    j
    • 2
    • 1
  • Failed to parse URL from [object Object]
    c

    cossinle

    04/01/2023, 10:14 PM
    My worker always gives this error when run in dev mode with the
    --local
    argument. As soon as I switch it off it starts working again though, I have no idea what's going on More details:
    Copy code
    [mf:err] GET /: TypeError: Failed to parse URL from [object Object]
        at new Request (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\undici\lib\fetch\request.js:81:15)
        at new Request (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\miniflare\node_modules\@miniflare\core\src\standards\http.ts:455:13)
        at EventTarget.dispatchFetch (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\miniflare\node_modules\@miniflare\core\src\index.ts:1077:51)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at Server.<anonymous> (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\@miniflare\http-server\src\index.ts:291:20)
    [mf:err] Cause: TypeError: Invalid URL
        at new NodeError (node:internal/errors:371:5)
        at onParseError (node:internal/url:552:9)
        at new URL (node:internal/url:628:5)
        at new Request (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\undici\lib\fetch\request.js:79:21)
        at new Request (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\miniflare\node_modules\@miniflare\core\src\standards\http.ts:455:13)
        at EventTarget.dispatchFetch (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\miniflare\node_modules\@miniflare\core\src\index.ts:1077:51)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at Server.<anonymous> (C:\Users\user\Documents\blogm-wrangler\blogm\node_modules\@miniflare\http-server\src\index.ts:291:20)
    GET / 500 Internal Server Error (502.63ms)
    s
    v
    • 3
    • 3
  • D1 or durable objects?
    s

    sjnsnsjxne

    04/09/2023, 12:09 PM
    I want to capture form contents on a landing page (Pages), perform some basic validation, and then insert the relevant info into an ERP system on a different domain via its REST API. I want this to work even if the ERP is temporarily down, so that a separate worker can check if the ERP is up at a regular interval and insert the values as soon as possible. Should I store the ā€œqueuedā€ values in a D1 instance or are durable objects suitable? The lifetime of durable objects vs KV seems a bit confusing to me, but I understand that KV would be unsuitable.
    z
    • 2
    • 2
  • Workers behavior
    z

    zarg129

    04/10/2023, 7:40 AM
    Hello, I'm working in small hosting company that primarily hosts marketing websites. We are using worker to handle some data so the question is: what if some of website will get an abuse? Would my worker or cloudflare account get a ban?
    w
    • 2
    • 2
  • Trying to make a simple cache using a cloudflare worker with hono.
    e

    Eli

    04/10/2023, 9:19 AM
    I was wondering if anyone could assist me with what I thought was going to be a simple usage of the cache api. My issue is that I cannot seem to get the cache to store the body properly... The cache key is getting stored and properly invalidated after 10 seconds but the body is always an empty object when the cache is matched.
    Copy code
    typescript
    app.get('/events', async (c) => {
      try {
        const cacheUrl = c.req.url
        const cache = caches.default
    
        // Check if our response is already in the cache
        let response = await cache.match(cacheUrl)
        console.log('body', JSON.stringify(response?.body))
    
        if (!response) {
          const { email } = c.req.query()
          const config = getConfig(c.env)
          const events = await findEvents(email, config)
    
          response = new Response(JSON.stringify({ data: events }))
          response.headers.append('Cache-Control', 's-maxage=10')
    
          c.executionCtx.waitUntil(cache.put(cacheUrl, response.clone()))
    
          return c.json({
            data: events
          })
        } else {
          console.log(`cache hit for ${cacheUrl}`)
        }
    
        return response
      } catch (err: Error | any) {
        return c.json(
          {
            error: {
              message: err.message
            }
          },
          500
        )
      }
    })
    The logs are showing up as this with an empty body when hitting the cache.
    Copy code
    json
    {
      "outcome": "ok",
      "scriptName": "some script name",
      "exceptions": [],
      "logs": [
        {
          "message": [
            "body",
            "{}"
          ],
          "level": "log",
          "timestamp": 1681117743889
        },
        {
          "message": [
            "cache hit for https://someurl/events?email=someemail@email.com"
          ],
          "level": "log",
          "timestamp": 1681117743889
        }
      ],
      "eventTimestamp": 1681117743883,
      "event": {
        "request": {
          "url": "some url",
          "method": "GET",
          "headers": {
            "content-type": "application/json"
          }
        },
        "response": {
          "status": 500
        }
      },
      "id": 27
    }
    k
    • 2
    • 4
  • The CNAME content contains . at last, but Cloudflare sames automatically remove that
    s

    Ssiswent

    04/10/2023, 9:31 AM
    This maybe makes something wrong. I can't validate even I have added these records.
    j
    • 2
    • 3
  • Received a FetchEvent but we lack a handler for FetchEvents.
    p

    ps

    04/10/2023, 4:38 PM
    I have an email worker. export default { async email(message, env, ctx) { const block = ["test@example.com"] if (block.indexOf(message.headers.get("from")) == -1) { await message.forward("me@domain.co.uk"); } else { message.setReject("Address is blocked"); } } } It seems to work but it says all runs have failed and I get the error Uncaught (in response) Error: Handler does not export a fetch() function.
    w
    • 2
    • 2
  • Can a VPN be added to Cloudflare Workers for API security?
    p

    Pato

    04/10/2023, 5:39 PM
    Hey! I am currently using Cloudflare Workers for my API but I am concerned about the security of my data. While Cloudflare Workers offer features like HTTPS encryption, I am wondering if it's possible to add a VPN to Cloudflare Workers to add an extra layer of security to my API. Has anyone attempted this before? If so, what was your experience like and how did you go about implementing this solution? If it's not possible to use a VPN with Cloudflare Workers, what other options do I have to improve the security of my API? I would greatly appreciate any advice or suggestions that you may have on this topic. Thank you in advance for your help!
    w
    c
    • 3
    • 11
  • Increasing workers upload limits
    s

    Shivansh Vij

    04/10/2023, 9:55 PM
    I put in a request last week to have our workers limits increased because we want to upload WASM modules that are sometimes bigger than 5mb. Is there a way for us to get this request expedited?
    s
    • 2
    • 7
  • Would love to get some color(s) when using `wrangler tail` or `wrangler pages tail`...
    t

    TigersWay

    04/11/2023, 8:15 AM
    chalk and co do not seem to work. Anyone has any idea or advice?
    a
    • 2
    • 1
  • Invalidating a CDN cache in a Worker
    j

    Jonathan Norris | DevCycle

    04/11/2023, 3:49 PM
    Hey Cloudflare folks, We have a setup where we have a set of SDKs who connect to worker APIs where we access a set of CF CDN cached S3 JSON files in our workers. When those files are updated by one of our backend services we trigger the purge cache API to purge the CDN globally for that file. After that purge cache API request we also trigger a message, through a live SSE connection connected to all active SDKs for that project, to trigger a new request to our CF Worker APIs to fetch new configurations. Generally we see this setup work well as purging the CDN cache can be surprisingly fast, however there are situations where the local CDN cache in certain data centers haven't been purged yet. As a part of the SSE message and the request we make to our workers, we send the
    sseLastModified
    time that we use to compare against the
    Last-Modified
    header of the CDN response. We are struggling to figure out the best way to invalidate the local data center cache from the worker without triggering many new requests to the global purge cache API. The options we see are: - Call the global purge cache API: https://developers.cloudflare.com/cache/how-to/purge-cache/#purge-by-single-file-by-url - Will calling DELETE on the Worker Cache API invalidate the local cache for a fetch request to the CDN? (this wasn't clear in the docs): https://developers.cloudflare.com/workers/runtime-apis/cache/#delete - Can this be accomplished by using the
    cf.cacheTtl = 0
    property on our fetch request or some other property (we are an enterprise customer): https://developers.cloudflare.com/workers/runtime-apis/request/#requestinitcfproperties Thanks for your help! Jonathan Norris
  • 2 return fetch request
    l

    lokiwind

    04/11/2023, 4:02 PM
    Hello, I am using this workers code in front of my website, but when I use "return fetch(request);" instead of the return "fetch(url, init);" parameter in line 24, the post operation does not occur. How can I replace "fetch(url, init);" with "return fetch(request);".. `addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const ip = request.headers.get("CF-Connecting-IP"); const countryCode = request.headers.get("CF-IPCountry"); const response = await fetch("https://mypage.xx/ip.txt"); const text = await response.text(); const ipInfo = text.trim().split('\n').find(line => line.startsWith(ip)); if (ipInfo) { return fetch(request); } const url = "https://mypage.xx/public.php"; const data = new URLSearchParams({ "data":
    ${ip}|${countryCode}
    }); const init = { method: "POST", body: data }; return fetch(url, init); } `
    v
    • 2
    • 1
  • Empty KV eventhough preview KV has values during Vitest
    f

    F0rce

    04/11/2023, 7:48 PM
    Hello everyone, basically the title already tells what my problem is, which I can't seem to get to work. Basically with a CI pipeline I want to test my worker (which is basically a REST api). It should use the preview KV I am using in development. But the KV is always empty. It seems like in my implementation it is using the production KV. Could anyone help me with it ?
    Copy code
    ts
    import { unstable_dev } from "wrangler";
    import type { UnstableDevWorker } from "wrangler";
    import { describe, expect, it, beforeAll, afterAll } from "vitest";
    
    describe("API", () => {
      let worker: UnstableDevWorker;
    
      beforeAll(async () => {
        worker = await unstable_dev("src/index.ts", {
          config: "wrangler.toml",
          experimental: { disableExperimentalWarning: true },
        });
      });
    
      afterAll(async () => {
        await worker.stop();
      });  
    
    it("should return test user", async () => {
        const resp = await worker.fetch("/api/v1/users/<id>", {
          headers: { "X-Auth-Token": "shared-key" },
        });
        if (resp) {
          const json = await resp.json();
          expect(json).toMatchObject({
            email: "user-mail",
          });
        }
      });
    });
  • Subdomain Problem
    s

    StreoidVoid

    04/12/2023, 10:32 AM
    I have problem with my domain name. Somehow somebody create subdomain without my permission and google search console get all index (135k index). How i solve this problem ?
    j
    • 2
    • 3
  • Verified Bots
    o

    onurrry

    04/12/2023, 12:23 PM
    Hello, how can I find out if the request to the workers is a verified bot?
    k
    • 2
    • 3
  • Getting the IP hono
    z

    Zetax

    04/12/2023, 1:49 PM
    Hey there, quick and simple question: Is there a way to get the IP of the client who is sending a request to the worker via hono? Because I can't seem to find it on the docs
    k
    • 2
    • 2
  • Invalid character DOMException2 with hono
    z

    Zetax

    04/13/2023, 1:23 AM
    Hey there, I've recently started using hono and everything has been going great so far, but now I am suddenly getting this:

    https://i.imgur.com/yQ7MxRA.pngā–¾

    error when trying to login with my credentials. The route responsible for the error contains this code: https://gist.github.com/Finninn/404c2cf942cfaae28add3be2465ff412 after line 110, at least that's what I assume because all console logs before that work fine and then it crashes the server. I really hope someone here can help me with the problem!
    • 1
    • 1
  • workers (DO), service binding --local
    d

    Dio

    04/13/2023, 7:07 AM
    guys are trying to use service binding. There are 2 worker A "user" DO and a "parser" DO. I've written service binding in "parser "config. I run -local 2 worker . I try to get it via env.user, but I see there is no «user» in parser env, although at start it says that there is service binding in console inside worker there is access to service binding, but not inside DO. How can this be solved?
    • 1
    • 1
  • Single WebSocket + multiple durable objects + proxies
    z

    Zoltan

    04/13/2023, 11:22 AM
    Hello, I'm setting up a Worker/WebSocket + Durable Objects combo where I need to support a single WS connection from the client to multiple Durable Objects. So far, I set up the DO class that responds with a WS and a Worker that responds with another WS for the client, when the latter receives a message from the client it connects to the DO with
    new WebSocket()
    using the unique ID from the message. First I tried Service Bindings but that doesn't seem to support WebSockets yet. Then I tried this
    new WebSocket()
    connection but was getting 404 instead of 101 without hitting DO at all, after some trial and error and getting 1024 from a dummy fetch request, I found that CF doesn't allow connecting two Workers within the same account. So then I opened another account and set up the DO there. This worked but I would need to duplicate half my infrastructure to this second account in order to have all the Service Bindings and KV stores. This is less than ideal. Now, I'm trying to set up a simple WebSocket proxy on this 2nd account. ie.: Client -> Single WS (Account 1) -> Proxy (Account 2) -> DO WS (Account 1) -> Client My understanding is that this should just work by CF magic passing around the request but the WS keeps disconnecting right after connecting without any errors. I tested a simple fetch on the proxy and that worked. So I tried setting up a manual proxy where I listen for messages from the ws pair and pass it along to the DO, this seem to establish a persisting connection but nothing happens with the messaging. Not getting any errors just silently failing. I would appreciate any insights or suggestions.
    • 1
    • 2
  • Legacy worker environment overwrite with wrangler2
    t

    Tino

    04/13/2023, 2:06 PM
    Last year i created a worker that was published with 2 dash environments (staging and production) Recently i updated the code to use wrangler2 with publish command and what this did was generate a new worker in cloudflare based on the --env flag provided "wrangler publish --env production", this was not what i wanted (2 workers instead of 1, resulting in 3 workers where one is the older legacy that is bound to a durable object per legacy environment to make things worse). The problem is that i want to overwrite the old worker for each environment. (keeping the durable object binding intact per env) I managed to do this by specifying the name of each environment in the toml file but when i publish it only seems to update the code for the main environment that is currently set to staging. (resulting in not being able to update production env, only environment vars) Any ideas how i would overwrite the code for the production based on the --env environment, possibly by setting it up in the toml file ? -------- Old situation with one worker with 2 environments (production,staging): example-worker_staging example_worker_production New situation with two workers with 1 environment (production) example-worker-staging example-worker-production
    j
    • 2
    • 7
  • Websockets time out after exactly 2 mins and 30 seconds
    l

    lgraz

    04/13/2023, 6:26 PM
    Hi there. I am using websockets in a live chat application but I'm having issues with the connection timing out (or at least this is what I assume is happening). We are using heartbeats/pings but this still happens. Am I running in to a limitation? If so I have not been able to find any documentation about it. Any advice would be appreciated.
  • how to secure API with JWT/Auth0
    p

    PeterMbanugo

    04/13/2023, 8:04 PM
    Does anyone have a reference as to how to secure worker code/API using JWT or Auth0? I made a tweet about it but I was also hoping to find some help here. https://twitter.com/p_mbanugo/status/1646595393705111553?s=46&t=iWa65mdWgjwDViR7T4qhgw
    s
    f
    • 3
    • 3
  • Orchestrate long running workers
    b

    bret_pat

    04/13/2023, 9:30 PM
    Background information I have a business use case that I'm trying to figure out how to implement in workers or if workers aren't a good solution for my situation. A user can start a long running task that consists of many sequential third party api calls. We want this long running task to be both cancellable (in case the user changes their mind mid-way), and throttle-able across all users so that we don't bring down the 3rd part API. We'd want to know when a task has officially cancelled and not just when the cancel as requested, since we would likely want to start a new task after the previous one has officially completed. Current thoughts on implementation We'd have to break down our long running task into multiple sequential workers for a specific task, so that one continues after the previous one has ran out of CPU time. The biggest CPU sink would be just parsing the json that we get from the 3rd party api. Maybe a durable object (that shows which tasks should be active) + a queue that has all of the requests of long running tasks? How would we be able to implement a long-running task consisting on multiple sequential workers, prerably bundled since we're mostly waiting on API calls?
    • 1
    • 1
  • How to access CF-Ray header?
    u

    user6251

    04/13/2023, 10:54 PM
    After enabling the "Managed Transform" to "Add visitor location headers", I am able to access
    cf-ipcountry
    and
    cf-ipcity
    . However, when I use the same approach to access
    cf-ray
    , it's always null:
    request.headers.get('cf-ray')
    Has this header been discontinued or do I have to enable it somewhere like the location headers? https://developers.cloudflare.com/fundamentals/get-started/reference/http-request-headers/#cf-ray
    c
    • 2
    • 2
  • How to deploy Shopify hydrogen V2 to Cloudflare workers?
    x

    xnslx

    04/14/2023, 12:29 AM
    I finally deploy hydrogen to Cloudflare workers, but it kinda of losing all the css styling. Does anyone encounter the same issue and how to resolve it? Many thanks!
    j
    • 2
    • 5
  • AWS Route 53 domain on Worker
    j

    Julius

    04/14/2023, 3:56 AM
    Quite a simple question: Is it possible to host a Worker on a AWS Route 53 domain? If so, how exactly?
    k
    d
    • 3
    • 2
12345...10Latest