https://discord.cloudflare.com logo
Join Discord
Powered by
# workers-help
  • Guidance on Turborepo / Monorepo App Deployment to Cloudflare
    s

    Srd

    05/18/2023, 8:31 AM
    I am currently working on a project involving the deployment of various workers / pages in a Turborepo. Ideally, I'm aiming to trigger deployments only for the applications that have been updated, rather than deploying all applications with each change. This would certainly help streamline the process and optimize resources. Does anyone have a reference or guide that provides a step-by-step procedure for achieving this? Any insights, suggestions, or resources would be much appreciated!
    f
    m
    m
    • 4
    • 6
  • Cron triggers happen multiple times, every time 2 times
    n

    Neiki

    05/18/2023, 9:36 AM
    Hey so my problem is that my 10 minutes cron trigger run and execute twice but i only setup one and handle one, that happend randomly yesterday without any changes of my side. I switched the timer now to 8 minutes and 15 minutes and all works fine, only one execute but if i switch back to 10 minutes it runs again twice all 10 minutes My Scheduled Handler:

    https://cdn.discordapp.com/attachments/779390076219686943/1108663705291468841/image.png▾

    my wrangler.toml cron settings:

    https://cdn.discordapp.com/attachments/779390076219686943/1108663742893400074/image.png▾

    past cron logs:

    https://cdn.discordapp.com/attachments/779390076219686943/1108650363319504926/image.png▾

    you can see twice execution cron dashboard settings:

    https://cdn.discordapp.com/attachments/779390076219686943/1108650363604701224/image.png▾

    https://cdn.discordapp.com/attachments/1108689633295999007/1108690021936017418/image.png▾

    m
    t
    l
    • 4
    • 16
  • Cron events happen multiple times every time
    g

    Gamengineer314

    05/18/2023, 2:38 PM
    Hello! I've just received an email saying that I reached 50% of the daily limit for KV for a project that I haven't modified in months and for which the route is disabled. So I checked the cron events logs and I noticed they are called 3 times every time 🤔 I don't understand why and today is the first time it happens.

    https://cdn.discordapp.com/attachments/1108765496087679038/1108765634566836305/image.png▾

    https://cdn.discordapp.com/attachments/1108765496087679038/1108765634885591120/image.png▾

    s
    • 2
    • 14
  • Weird error
    j

    Jerasaurus

    05/18/2023, 11:49 PM
    Hello! im trying to allow a domain through CORS using https://developers.cloudflare.com/workers/examples/cors-header-proxy I have a frontend sitting at domainA.com that calls an api at domainB.com for some reason I get this whenever a request fails
    Copy code
    workerd/server/server.c++:2347: error: Uncaught exception: kj/async-io-win32.c++:385: failed: WSARecv(): #64 The specified network name is no longer available.
    stack: 7ff680e88950 0 0 0 0
    doesnt seem like its a workers issue since stack overflow wasnt helpful but also I may be doing this all wrong (exact code https://pastebin.com/dT4G1xnE)
    i
    e
    +2
    • 5
    • 44
  • Requests to worker getting canceled when trying to redirect
    a

    attfarhan

    05/19/2023, 7:28 AM
    I have a Worker deployed that handles redirections for users based on their experiment grouping for an A/B test. The Worker handles 4 cases: * If the user has an existing analytics cookie, and the user is in: - the control group - the variant group * If the user has no analytics cookie yet (i.e. is a new user), and the user is in: - the variant group - the control group For the variant group cases, the worker redirects users to the experimental URL:
    Copy code
    const statusCode = 302
    const resp = new Response(null, {
      status: statusCode,
      headers: new Headers({ Location: EXPERIMENTATION_URL }),
      })
    return resp
    For the control group, we send the user through to the original site they requested:
    Copy code
    let resp = await fetch(request)
    resp = new Response(resp.body, resp)
    resp.headers.append("Set-Cookie", newCookie) // only if they have no cookie yet
    return resp
    However, for some reason, in about 50% of the cases that we hit the case where the user has no analytics cookie yet, and is in the control group, the request in the Worker logs shows up as canceled. A few seconds after the canceled request, there is usually a successful request, which seems to be a retry, but this results in the user being assigned to a variant group. This case is the last case to get handled in the Worker code. However, I am a bit baffled as this is the only case that fails. Is there any way to check why these requests are being canceled? Or are there any common reasons why requests get canceled, especially if the requests only get canceled in a specific code path ?
  • Adding Variables to workers fails with error code 10075
    s

    Slotherman

    05/19/2023, 7:51 AM
    Hi there, I'm trying to add an R2 binding to my (free) Worker, but I get the error message:
    Copy code
    Workers Unbound has not yet been enabled for this account. (Code: 10075)
    I don't have any other variables yet, so I assume this would be allowed. I can't seem to find much information on this. Does anybody know how to resolve it other than by credit card? 🙂
    e
    • 2
    • 17
  • Wrangler@3 -- wrangler dev uses random port all the time
    f

    F0rce

    05/19/2023, 9:52 AM
    Hello everyone, before upgrading to wrangler@3 (and now using the fully local development mode) the port was normally on
    8787
    . Now each start of the environment seems to have a random port (at the time of trying its
    64278
    ). As the Port is not always the same and a new restart creates a new port, it is a pain to update the development frontend env or my api testing client (insomnia) to always be at the correct port. Is this a bug on macOS or is there a way to force the port to be at 8787 ? Thanks in advance, David
    h
    • 2
    • 7
  • Rewriting CSS
    t

    ttraenkler

    05/19/2023, 11:25 AM
    Does html-rewriter have support for css or is there something equivalent?
    h
    • 2
    • 2
  • Client disconnections
    s

    sdan

    05/19/2023, 11:47 AM
    it seems like a lot of clients are being disconnected. how can i debug / be able to properly handle that? can i respond with something right before its disconnected?

    https://cdn.discordapp.com/attachments/1109085025988771890/1109085026248835112/Screenshot_2023-05-19_at_4.46.49_AM.png▾

    i
    • 2
    • 2
  • Error: Script startup exceeded CPU time limit. [code: 10021] when using static import
    s

    super_pispis

    05/19/2023, 2:02 PM
    When I static import some wasm libraries, I often get the error
    Error: Script startup exceeded CPU time limit. [code: 10021] when using static import
    when deploying. It is resolved when I use dynamic import (
    import('...
    ), but dynamic import apparently doesn't work with wasm. Any suggestions?
    i
    • 2
    • 24
  • Cron triggering twice
    b

    Bhone M Min

    05/19/2023, 2:29 PM
    In the past two days my cron trigger has been triggering twice. I've set only one trigger at 8:00 UTC but it is triggering twice within the minute. I've searched in this forum and I've found someone also encountered the same situation but seems like it resolved itself without any of their action.

    https://cdn.discordapp.com/attachments/1109125738348675092/1109125739124629554/image.png▾

    https://cdn.discordapp.com/attachments/1109125738348675092/1109125739606982697/image.png▾

    s
    • 2
    • 2
  • Html rewriter issue with hono v3.0.0 or superior
    t

    TheStuntback46

    05/19/2023, 4:08 PM
    Hello does anybody uses hono v3.0.0 or superior with html rewriters it seems not working for us. Context.res seem immutable...
    h
    • 2
    • 1
  • Fetching external sitemap.xml no response
    o

    Operator

    05/19/2023, 5:44 PM
    Hi there, I'm trying to use cloudflare worker to change the instances of hostname of a sitemap that is generated by Webflow. We have to use this method as our webflow is reverse-proxied but Webflow customization is a bit lacking and won't use the global canonical URL in the auto-generated sitemap.xml. Gist of what I'm doing is fetching the actual webflow sitemap.xml, replacing all instances of the hostname with what we want to be user-facing and SEO-facing, serving the modified sitemap.xml. I'm having an issue where cloudflare worker is getting no response when fetching. The sitemap resource is public and works fine in postman GET.
    Copy code
    async function handleSitemap() {
      const sitemapUrl = 'https://tempsite.com/sitemap.xml'
      
      const headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',
        'Accept-Language': 'en-US,en;q=0.9'
      }
    
      let response = await fetch(sitemapUrl, {method: 'GET', headers: headers})
      console.log(response.body)
    
      if (!response.ok) {
        throw new Error('No response!')
      }
      
      let data = await response.text()
      const contentType = response.headers.get('content-type')
    
      // Replace 'tempsite.com' with 'mysite.com'
      data = data.replace(/tempsite\.com/g, 'mysite.com')
    
      return new Response(data, {
        headers: {
          'content-type': contentType
        }
      })
    }

    https://cdn.discordapp.com/attachments/1109174734966493274/1109174735109111820/image.png▾

    • 1
    • 1
  • Accept media and pipe to two locations.
    e

    embed

    05/20/2023, 4:42 AM
    Hey all! I am working on UGC file uploading in my app. This goes through a CF Worker. I am wondering how I would go about piping the media from the worker to one API (for checking for illegal content pre upload) and afterward piping that to an s3 bucket via aws4fetch. Anyone know how I would go about it?
  • Detect when worker was invoked via service binding
    m

    Matt

    05/20/2023, 7:14 AM
    Hi there, how do I detect whether my worker was invoked via a HTTP Route or via a service binding from another worker? I would like to skip auth + implement custom logic in the latter scenario
    c
    • 2
    • 1
  • Map not saving in TypeScript
    n

    nexpid

    05/20/2023, 8:09 AM
    i have a really weird bug when working with cloudflare workers (compiling from typescript) when I set some data to a Map from command.ts, all entries disappear in callback.ts code: https://tsplay.dev/NVRlqN

    https://cdn.discordapp.com/attachments/1109392374318243952/1109392374490222612/image.png▾

    https://cdn.discordapp.com/attachments/1109392374318243952/1109392374779609148/image.png▾

    i
    • 2
    • 4
  • TLS error on wrangler dev after update to 3.0.0
    s

    subhendupsingh

    05/20/2023, 11:05 AM
    After updating to wrangler 3, I am getting this error
    Copy code
    workerd/jsg/util.c++:276: error: e = kj/compat/tls.c++:215: failed: TLS peer's certificate is not trusted; reason = unable to get local issuer certificate
    stack: 7ff6229c8a6f 7ff622a0c9dd 0 0 0 0 0 0 0 0 0 0 0 0 7ff6229d6234; sentryErrorContext = jsgInternalError
    Even when i explicitly pass the --local-protocol http
    Copy code
    npx wrangler dev src/index.ts --local-protocol http
    c
    • 2
    • 5
  • CORS issue even when CORS header are added
    b

    Bamboo

    05/20/2023, 11:16 AM
    My workers script with d1 binding, and '/api/view/customers_data' on GET request is succesful but sending POST request with body to '/api/add/customer' giving error Fetch request
    Copy code
    const response = await fetch(
            "https://xxxx.xxxxx.workers.dev/api/add/customer",
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
            id: xxx,
            cabin: xxxx,
            name: xxxx
          },)
            }
          );
    // Workers Script
    Copy code
    export default {
      async fetch(request, env, ctx) {
        const corsHeaders = {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': '*',
          'Access-Control-Allow-Methods': 'GET, POST',
        };
        const { pathname } = new URL(request.url);
        try {
          if (pathname === "/api/view/customers_data") {
            const results = await env.DB.prepare(
              "SELECT * FROM customers_data "
            ).all();
            return new Response(JSON.stringify(results), {
              headers: corsHeaders,
            });
          }else if (pathname === "/api/add/customer") {
            const body = await request.json();
            const results = await env.DB.prepare(
              "INSERT INTO customers_data (cabin, name, email, phone, gender) VALUES(?1, ?2, ?3, ?4, ?5)"
            ).bind(body.cabin, body.name, body.email, body.phone, body.gender).run();
    return new Response(JSON.stringify(results), {
              headers: corsHeaders,
            });      }
        } catch (e) {
          return Response.json(e);
        }
       
        });  
      }
    };
    //Error Access to fetch at 'https://xxx.xxxx.workers.dev/api/add/customer' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    m
    i
    • 3
    • 13
  • I'm not able to access/edit the worker script anymore since 2 days ago
    d

    D I

    05/20/2023, 4:05 PM
    What gives?

    https://cdn.discordapp.com/attachments/1109512260323397652/1109512261187408002/image.png▾

    i
    p
    • 3
    • 12
  • Unknown Event - Exceeded CPU Limit with Unbound Worker
    d

    daver

    05/20/2023, 8:11 PM
    I have a Rust worker bound to a queue. It gets
    Unknown Event - Exceeded CPU Limit
    errors without doing very much, e.g. just deserializing the message batch exactly as in the
    worker-rs
    example for queues. This happen with a single message. I tried setting
    usage_model=unbound
    in wrangler.toml and I see it picked up in the UI, but the error persists. Am I missing something obvious?
    • 1
    • 1
  • Skipping a module when bundling
    h

    happenator

    05/20/2023, 8:40 PM
    Has anyone found a way to skip a module dependancy when bundling? I'm using
    googleapis
    , which has a
    require('http2')
    while
    http2
    isn't available in the runtime. That might be fine -- I think I can pass runtime options to avoid using it. I just need to find a way to get
    esbuild
    to ignore the missing dependancy.
  • KV Assets (site bucket) __STATIC_CONTENT is are suffixed with hashes (05c5fa8db8)
    i

    ItsWendell

    05/20/2023, 10:09 PM
    Hi all, We're trying to use a workers sites bucket defined in our API wrangler to host some (temporary) image assets in to show in our app, but once we attempt to fetch these we see that they are suffixed with hashes. What is the recommended way to continue here so we can access assets in these buckets through e.g.
    /public/some-temp-image.png
    ? We use getAssetFromKV:
    Copy code
    return await getAssetFromKV(
          {
            request: ctx.req.raw,
            waitUntil: ctx.executionCtx.waitUntil.bind(ctx.executionCtx),
          },
          {
            ASSET_NAMESPACE: ctx.env.__STATIC_CONTENT,
            mapRequestToAsset: (req) => {
              const url = new URL(req.url);
              url.pathname = url.pathname.replace(/^\/public/, "");
              return new Request(url.toString(), req);
            },
          },
        );
      } catch (e) {
        if (e instanceof Error) {
          console.error(e);
          if ("status" in e) {
            if (e.status === 404) {
              return ctx.notFound();
            }
          }
        }
        throw e;
      }
    Can we skip workers sites from adding these hashes?
    j
    • 2
    • 4
  • Robots.txt / indexing problem with site running as pages
    d

    D I

    05/20/2023, 10:51 PM
    Running into a situation where Google search is unable to index the site running as pages. Robots.txt renders as index.html for some reason. I did create explicit robots.txt in my repo and I'm pretty sure it's propagating to pages - anyone know what might be happening?
    j
    i
    • 3
    • 10
  • Migration to module not working .json()
    s

    sideshot

    05/21/2023, 2:10 AM
    I'm converting my worker to module but the part where it gets posted data request.json() is no longer working. What am I doing wrong? I verified the payload is being sent. async fetch(request, env, ctx) { request.json() // return null }
    k
    j
    • 3
    • 7
  • New Quick Edit(VS Code Web) won't work in Chinese
    s

    SakuraPY

    05/21/2023, 4:25 AM
    Hi there. When I tried to use Quick Edit while the browser language is Chinese Simplified/Traditional/Hong Kong, the Quick Edit will just white out, while other languages won't (even those minor languages can still be loaded, the Quick Edit will just be presented in English). I guess this is a localization issue. Please fix it. Thanks a lot.
    s
    • 2
    • 2
  • Can cloudflare's api gateway be used to rate-limit workers api?
    u

    0xAsimetriq

    05/21/2023, 1:06 PM
    I'm wrapping up development of my api on top of Cloudflare's workers and am about to start setting up rate-limitting. Initially wanted to do this via serverles redis, but it looks like WAF https://developers.cloudflare.com/waf/ achieves the same. But I cant manage to find this setting under my workers page. I believe it is only available for domains? Am I correct in assuming that in order to limit my workers routes, I can only do so when custom domain is set up for it?
    i
    • 2
    • 1
  • Get current worker via wrangler?
    s

    sideshot

    05/21/2023, 4:15 PM
    I created a few workers directly using the dashboard. Is there a way PULL a current worker into a folder via wrangler? The online "quick edit" isn't working right now, and I'd like to start using it via vscode.
    s
    j
    u
    • 4
    • 4
  • Your Worker failed validation because it exceeded startup limits. Global Scope.
    f

    Felix || TM9657

    05/21/2023, 6:16 PM
    I love developing with workers, however I continue to get errors about the startup limits (CPU time). They seem quite random and hard to debug. Pushing multiple times sometimes works. Coming from AWS Lambda, the global scope is no bad place to cache certain data. How should we do that in Cloudflare workers? E.g. Reusing Database Connections etc. Let´s take this code, it wont deploy, however I am not doing anything in the global scope at coldstart:
    Copy code
    js
    import {
      AICache,
      authorize,
      CorsResponse,
      OpenAIStreamHandler,
    } from "@tm9657/backend-worker";
    import GPT3Tokenizer from "gpt3-tokenizer";
    import { Configuration, OpenAIApi } from "openai";
    
    export interface Env {
      DATABASE_URL: string;
      OPENAI_KEY: string;
    }
    
    type AIRequestBody = {
      prompt: string;
      system?: string;
      top_p?: number;
      frequency_penalty?: number;
      max_tokens?: number;
    };
    
    let cache: AICache | null = null;
    
    export default {
      async fetch(
        request: Request,
        env: Env,
        ctx: ExecutionContext
      ): Promise<Response> {
        const auth = await authorize(request);
        if (!auth) return new CorsResponse("Unauthorized", 401).finalize(request);
    
        const body: AIRequestBody = await request.json();
        if (!body || !body?.prompt)
          return new CorsResponse("Bad Request", 400).finalize(request);
        if (!cache) cache = new AICache();
        cache.init(env.DATABASE_URL);
        let openai: OpenAIApi = new OpenAIApi(
          new Configuration({
            apiKey: env.OPENAI_KEY,
          })
        );
    
        if (!openai)
          return new CorsResponse("Internal Server Error", 500).finalize(request);
    
        const usage = await cache.getUsage(auth.sub);
        if (!usage.getHardLimit())
          return new CorsResponse(
            "Monthly API limit hit, please upgrade your subscription!",
            429
          ).finalize(request);
    
        const tokenizer = new GPT3Tokenizer({ type: "gpt3" });
        const { readable, writable } = new TransformStream();
    
        const openAIRequest = await openai.createChatCompletion(
          {
            model: "gpt-3.5-turbo",
            messages: [
              { role: "system", content: body.system || "" },
              { role: "user", content: `${body.prompt}` },
            ],
            top_p: body.top_p || 0.05,
            max_tokens:
              4096 - tokenizer.encode(`${body.prompt} ${body.system}`).bpe.length,
            user: auth.sub,
            frequency_penalty: body.frequency_penalty || 1.0,
            stream: true,
          },
          { responseType: "stream" }
        );
    
        const writableStream = writable.getWriter();
    
        let total = "";
        const handler = new OpenAIStreamHandler(
          openAIRequest,
          async (message) => {
            total += message;
            await writableStream.write({ total, message });
          },
          async () => {
            await writableStream.close();
            await cache?.updateUsage(
              auth.sub,
              "chatGPT",
              tokenizer.encode(`${body.prompt} ${body.system} ${total}`).bpe.length
            );
          }
        ).promise();
    
        return new CorsResponse(readable).finalize(request);
      },
    };
    j
    • 2
    • 8
  • Cannot create binding for class in script ./rate-limiter.js that does not exist [code: 10061]
    s

    sideshot

    05/21/2023, 7:43 PM
    I'm trying to publish adding durable object to my worker. I have a new file in the project folder called rate-limiter.js. I'm getting this error, when running wrangler publish. * Cannot create binding for class in script rate-limiter that does not exist [code: 10061]*
    Copy code
    // rate-limiter.js
    export class APIRequestCounter {}
    
    }
    Copy code
    // index.js
    import { APIRequestCounter } from './rate-limiter.js';
    export default {
      async fetch(request, env, ctx) {
      }
    }
    TRY 1: WRANGLER.toml
    Copy code
    [durable_objects]
    bindings = [{name = "API_RATE_LIMITER", class_name = "APIRequestCounter", script_name = "rate-limiter.js"}]
    TRY 2: WRANGLER
    Copy code
    [durable_objects]
    bindings = [{name = "API_RATE_LIMITER", class_name = "APIRequestCounter", script_name = "rate-limiter"}]
    TRY 3: WRANGLER
    Copy code
    [durable_objects]
    bindings = [{name = "API_RATE_LIMITER", class_name = "APIRequestCounter", script_name = "./rate-limiter.js"}]
    w
    • 2
    • 10
  • Next.js site not rendering when using workers as reverse proxy locally
    s

    shrirambalaji

    05/21/2023, 11:35 PM
    Using workers as a reverse proxy for .example.com to return example.com/id. I've checked the network sources, and the assets are in deed coming through and not 404-ing. But there seems to be parsing error, somewhere.
    Copy code
    ts
    
    export default {
      async fetch(request: {
        url: string | URL; headers: { get: (arg0: string) => string } 
    }, env: any, ctx: any) {
        try {
          const subdomain = request.headers.get('host').split('.')[0];
          // ... map subdomain to id
          const destinationURL = new URL(`http://localhost:3001/${id}`);
          const response = await fetch(destinationURL);
          const proxyResponse = new Response(response.body, { headers: response.headers, status: response.status, statusText: response.statusText})
          return proxyResponse
        } catch (error) {
          return new Response(null, { status: 404, statusText: "Oops can't find that page" });
        }
      },
    };
    What am I missing here?

    https://cdn.discordapp.com/attachments/1109987865154310245/1109987865603084288/image.png▾

1...567...10Latest