https://discord.cloudflare.com logo
Join Discord
Powered by
# workers-help
  • Mocking fetch with Jest for a Cloudlare Worker
    j

    jpbrown84

    12/29/2023, 10:27 AM
    Hi all - i'm trying to figure out something that potentially could be very simple. I've got a Worker running on Cloudflare that pulls data from an external API, via fetch. Inside my 'fetchData.ts' I have the following.
    Copy code
    const response = await fetch(env.ENDPOINT, {
            method: "POST",
            headers: {
                Authorization: `Basic ${btoa(
                    `someKey`
                )}]`,
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: "someBody"
        });
    I'm trying to write a 'testData.test.ts' file to check that fetch was called with the correct args. If I was working with a node environment i'd just mock out node-fetch and check what the mock was called with. With the worker, fetch is global, so I have no idea what to mock. Any help with this would be much appreciated
    m
    • 2
    • 4
  • original email is not repliable means
    d

    DannyDanDan

    12/29/2023, 10:39 PM
    Hi guys, anyone know what Error: original email is not repliable means? I get it when i send an email to the worker it replies and i send an email back or try to, then i get that msg
  • Error: Failed to upload secrets.
    w

    willin

    12/30/2023, 11:17 AM
    https://github.com/willin/sso/blob/c445146f46d8acec953863253c96f743d1c29965/.github/workflows/deploy.yml#L54 Error: Failed to upload secrets. Error: 🚨 Action failed
    Copy code
    - name: Deploy API Service
            uses: cloudflare/wrangler-action@v3
            with:
              apiToken: ${{ secrets.CF_API_TOKEN }}
              command: publish --config wrangler.toml
              workingDirectory: apps/sso
              secrets: |
                AFDIAN_CLIENT_ID
                AFDIAN_CLIENT_SECRET
                AFDIAN_CALLBACK_URL
                ALIPAY_APP_ID
                ALIPAY_PRIVATE_KEY
                ALIPAY_CALLBACK_URL
                GITHUB_ID
                GITHUB_SECRET
                SESSION_SECRET
              # SESSION_KEY
              # GITHUB_CALLBACK_URL
            env:
              CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}
              AFDIAN_CLIENT_ID: ${{ secrets.AFDIAN_CLIENT_ID }}
              AFDIAN_CLIENT_SECRET: ${{ secrets.AFDIAN_CLIENT_SECRET }}
              AFDIAN_CALLBACK_URL: ${{ secrets.AFDIAN_CALLBACK_URL }}
              ALIPAY_APP_ID: ${{ secrets.ALIPAY_APP_ID }}
              ALIPAY_PRIVATE_KEY: ${{ secrets.ALIPAY_PRIVATE_KEY }}
              ALIPAY_CALLBACK_URL: ${{ secrets.ALIPAY_CALLBACK_URL }}
              GITHUB_ID: ${{ secrets.GH_CLIENT_ID }}
              GITHUB_SECRET: ${{ secrets.GH_CLIENT_SECRET }}
              SESSION_SECRET: ${{ secrets.SESSION_SECRET }}
              # SESSION_KEY: ${{ secrets.SESSION_KEY }}
              # GITHUB_CALLBACK_URL: ${{ secrets.GITHUB_CALLBACK_URL }}
    j
    d
    • 3
    • 3
  • Getting "Error: The script will never generate a response." When using a websocket with the worker.
    p

    PoisnFang

    12/31/2023, 3:08 AM
    Here is an example of what I am experiencing. I call ws.close() from the browser and I get the event just fine on the worker. The because the worker through the error I am also not able to track my CPU time. (I am using the standard pricing) https://github.com/grgbkr/cf-websocket-msg-limit/tree/master
  • Missing "Content-Length" from worker response
    y

    yigalavi

    12/31/2023, 8:53 AM
    I'm setting a response with these headers:
    Copy code
    const corsHeaders = new Headers({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Authorization, Content-Type',
        'Content-Type': 'application/json',
    });
    But I get responses without "Content-Length". do I have to add it manually? is the existence of 'Content-Type': 'application/json' make it so the length isn't added?
    • 1
    • 1
  • use D1 DB in worker (no wrangler etc, just JS)
    s

    spuckwaffel

    12/31/2023, 11:56 AM
    hey there, noobie here. There are multiple tutorials online how to set up the D1 DB with a worker using wrangler, nodejs etc., however i just want to be able to use all the db related stuff within my js file, so no typescript. I went ahead and added the database via DB Database bindings in the settings of the worker, however any request i do in js returns empty data:
    Copy code
    js
    const { results } = await env.DB.prepare('SELECT * FROM user').all();
    const json = await Response.json(results);
    const jjson = JSON.stringify(json);
    console.log(jjson);
    and yes, the DB is called user, the environment variable in the settings is DB. Am i missing something?
    k
    h
    • 3
    • 10
  • Is there any way to allow for eval() on a worker?
    u

    <Evie.Codes>

    01/01/2024, 10:40 PM
    I understand that there are serious security issues with using eval() as a general rule. My problem is that I'm using a library called
    serialize-javascript
    to be able to stringify structures beyond what JSON.stringify(). Specifically, serialize-javascript allows for serializing dates, maps, sets, functions, regex and bigint. However, it doesn't provide any deserialize method, and simple states to use eval(). Which works perfectly well and has for years... but trying to port my db wrapper to a worker-supported version has cause me a fair share of grief. I would rather not remove functionality from my module due to this limitation, though I do understand that the distinction is that the context of running in a worker means we're not only dependendent on the user's system and security, but yours.
    k
    m
    • 3
    • 7
  • Wildcard worker route not working, no errors in panel
    j

    Joey

    01/02/2024, 10:25 PM
    I'm trying to create a route to my worker, it's a basic script that just returns the url you are accessing it at. In the panel, under my worker, I have a custom domain set as example.mysite.com, and a route for *.example.mysite.com, with the zone of mysite.com Visiting the custom domain works as expected, but trying to visit the custom route results in no page loading, as if there is no dns record set for it. Am I misinterpreting how routes work here?
    e
    • 2
    • 4
  • Socket response time >=150ms ?
    n

    Nikil

    01/03/2024, 12:05 AM
    I was under the impression that with Websockets and Durable Objects, we could get short response times, like <50ms. I'm just sending json objects. But I'm getting like 500ms to 1.5s. I'm operating a live Q&A service. Maybe I'm being dumb by sending the latest status of all of the questions when somebody upvotes a question or asks a new one so I can make sure we don't have weird consistency issues between clients, so I'm send around 1.7MB when there are ~400 questions. However, I deleted all the questions and tried it and I'm still gettting around the same timing. I'm measuring the timing using K6 socket testing. What could I be doing wrong? How can I make this more performant (<50ms or at least <100ms)? @squareee
    e
    m
    k
    • 4
    • 42
  • CouchDB compatible API on CloudFlare
    t

    telgareith

    01/03/2024, 1:00 PM
    I'm interested in getting https://obsidian.md 's third party sync (https://github.com/vrtmrz/obsidian-livesync) working. However, it requires a CouchDB to share the sync. Is there an existing solution? Maybe KV + Workers + ??? Could be coded to do it.
  • Worker Queue retries immediately and exhausts retries.
    c

    codeoholic

    01/03/2024, 2:29 PM
    When I make a queue message retry due to the pending task, queues goes 10 reattempts within seconds. While the batch size is 100 and batch timeout is 10s in settings. Thus dropping the message from the queue.
  • how to create a mock or test Request with valid cf `IncomingRequestCfProperties` properties?
    s

    snowcode

    01/03/2024, 4:18 PM
    I need to write some integration tests for my worker; and I'm unable to set the cf properties of a Request which my code relies on; which mean's it's very difficult to write super effective unit tests; I'd like to use a real Request object, instead of trying to create a fragile test double. (which is what I'm currently doing and its caused me a lot of problems that using the real object would melt away) Here's the problem; this test fails, and it should pass.
    Copy code
    ts
        it('Must be able to create mock Request with cf user init', function() {
            const user  : IncomingRequestCfProperties = TestUsers.cfCambridgeUser       
            const init : RequestInit = {
                method: 'GET',
                cf: user
            };
            const newRequest = new Request('https://example.com', init);
            // Check if cf properties are set
            console.log(">>> newRequest.cf >>>" , newRequest.cf);
            assert.ok(newRequest.cf!==undefined)
        })
    This should pass; but the value get's removed (undefined) after it's been set/requested via RequestInit. (ignored) Here's the definition for RequestInit; in CF's worker-types package
    Copy code
    ts
    interface RequestInit {
      method?: string;
      headers?: HeadersInit;
      body?: BodyInit | null;
      redirect?: string;
      fetcher?: Fetcher | null;
      /**
       * cf is a union of these two types because there are multiple
       * scenarios in which it might be one or the other.
       *
       * IncomingRequestCfProperties is required to allow
       *   new Request(someUrl, event.request)
       *
       * RequestInitCfProperties is required to allow
       *   new Request(event.request, {cf: { ... } })
       *   fetch(someUrl, {cf: { ... } })
       */
      cf?: IncomingRequestCfProperties | RequestInitCfProperties;
      signal?: AbortSignal | null;
    }
    Does anyone know how to create a mock or real Request** using RequestInit?** Thanks in avance, Al
    • 1
    • 1
  • Worker Route Only Working for Naked Domain
    z

    zavierbythebeach

    01/03/2024, 4:39 PM
    Hello All, I could use a second set of eyes here and hoping someone can help. I have a worker setup with a route enabled. The worker itself works great but only on one of the routes. The other route is completely ignored and goes to our origin which of course returns a 404. The route is:
    *website.com/images*
    The following works: https://website.com/images but the following does NOT work: https://www.website.com/images I've looked at any and all transform, redirect rules. Other workers that may have a conflicting route and nothing appears to be in place that would interfere with this route. Any assistance would be appreciated. Thank you!
    s
    • 2
    • 4
  • Struggling with websockets and durable objects
    t

    thisisntme.

    01/03/2024, 4:51 PM
    Copy code
    ts
    export interface Env {
        COUNTER: DurableObjectNamespace;
    }
    
    // Worker code:
    
    export default {
        async fetch(request: Request, env: Env) {
            let url = new URL(request.url);
            let name = url.searchParams.get('name');
            if (!name) {
                return new Response('Select a Durable Object to contact by using' + ' the `name` URL query string parameter, for example, ?name=A');
            }
    
            let id = env.COUNTER.idFromName(name);
    
            // Construct the stub for the Durable Object using the ID.
            // A stub is a client Object used to send messages to the Durable Object.
            let obj = env.COUNTER.get(id);
    
            // Send a request to the Durable Object, then await its response.
            return obj.fetch(url);
        },
    };
    
    // Durable Object
    
    export class Counter {
        state: DurableObjectState;
        webSockets: Set<WebSocket>;
        constructor(state: DurableObjectState, env: Env) {
            this.state = state;
            this.webSockets = new Set();
        }
        // Define the broadcast function
        broadcast(message: string) {
            this.webSockets.forEach((ws) => {
                ws.send(message);
            });
        }
        // Handle requests sent to the Durable Object
        async fetch(request: Request) {
            // Apply requested action.
            let url = new URL(request.url);
            // Check for websocket request
            console.log('DURABLE OBJECT', request.headers.get('Upgrade'));
    
            if (request.headers.get('Upgrade') === 'websocket') {
                const pair = new WebSocketPair();
                const { 0: clientWebSocket, 1: serverWebSocket } = pair;
                serverWebSocket.accept();
                this.webSockets.add(serverWebSocket);
                let value = Number((await this.state.storage.get('value')) || 0);
                serverWebSocket.send(JSON.stringify({ value }));
                // Handle websocket messages from the client as the server
                serverWebSocket.addEventListener('message', async (event) => {
                    let data;
                    if (typeof event.data !== 'string') {
                        serverWebSocket.send(JSON.stringify({ error: 'Invalid message format' }));
                        return;
                    }
                    try {
                        data = JSON.parse(event.data);
                    } catch (error) {
                        serverWebSocket.send(JSON.stringify({ error: 'Invalid JSON' }));
                        return;
                    }
    
                    let value = Number((await this.state.storage.get('value')) || 0);
    
                    switch (data.command) {
                        case 'increment':
                            value++;
                            break;
                        case 'decrement':
                            value--;
                            break;
                        default:
                            serverWebSocket.send(JSON.stringify({ error: 'Unknown command' }));
                            return;
                    }
    
                    await this.state.storage.put('value', value);
    
                    // Broadcast the updated value to all clients
                    this.broadcast(JSON.stringify({ value }));
                });
    
                // Remove the server websocket when it is closed
                serverWebSocket.addEventListener('close', (event) => {
                    this.webSockets.delete(serverWebSocket);
                });
    
                // return the client websocket
                return new Response(null, { status: 101, webSocket: clientWebSocket });
            }
        }
    }
    k
    • 2
    • 3
  • typescript durable objects transaction api
    t

    thisisntme.

    01/03/2024, 7:02 PM
    Is there an example of how to type durable objects in the storage api?
    Copy code
    ts
    state: DurableObjectState;
    webSockets: Set<WebSocket>;
    storage: DurableObjectStorage;
    constructor(state: DurableObjectState, env: Env) {
      this.state = state;
      this.storage = state.storage;
      this.webSockets = new Set();
    }
    I guess I'd want to define the type of stuff accessed through this.storage.get()/set()
    k
    • 2
    • 1
  • Force workers to only use IPv4 addressess?
    i

    Infinity Chief ∞ I WONT DM YOU

    01/03/2024, 10:03 PM
    I'm calling an upstream API using workers and they require me to whitelist IP addresses. The problem is that they only support IPv4. Is there a way to force workers to only use IPv4 or some way to reliably get one of the IPv4 addresses found in https://www.cloudflare.com/ips/?
    c
    e
    • 3
    • 7
  • is it to use the workers for security research purposes?
    h

    hazemhazem999

    01/04/2024, 1:01 AM
    Such as brute forcing web hosts, crawling web sites etc, all legaly ofcourse ( i have permision to do this research)
    f
    • 2
    • 4
  • [Cloudflare image resizing] persistent Error 9412 /HTTP 415 (apparently no origin revalidation)
    h

    hkhl.

    01/04/2024, 12:41 PM
    Hi, please direct me to a different channel if it fits better elsewhere. I am doing worker image resizing as described here: https://developers.cloudflare.com/images/image-resizing/resize-with-workers/. Works as designed in general, but when I bulk add images to the origin storage (public Azure Blob Storage), while some of the new images are already requested through the worker, we sometimes get images that are stuck in an error state. These requests then always return
    HTTP 415 Unsupported Media type
    and
    Cf-resized: err=9412
    long after the origin image upload is complete (~ 60 min.) The only way to fix this is to purge the complete cache in the dashboard manually. I did a lot of debugging, and I don't see why Cloudflare does not revalidate the origin. - There is no custom caching in the worker - The origin does not send cache-control headers. - Manually purging a single upstream URL as described here https://developers.cloudflare.com/images/image-resizing/troubleshooting/#caching-and-purging does not work. (So it is some kind of cache issue)
    • 1
    • 1
  • I want to do some file operations using ffmpegA
    r

    ranjan_mangla

    01/04/2024, 5:24 PM
    I want to do some file operations using ffmpeg as soon as a file is uploaded to my storage bucket, and then want to upload the resulting files to another R2 storage bucket. I have gone through the doc, but can't figure out how to do it. can someody please help
  • node:crypto functions
    j

    Joey

    01/05/2024, 8:37 AM
    I'm trying to use node:crypto functions in my code, but I am receiving errors. I get the error attached in the IDE. But then I get intellisense which shows me those crypto functions. I have the compatibility_flags = [ "nodejs_compat" ] in my wrangler.toml.
    k
    • 2
    • 4
  • Problem with multiple files (like default router/proxy template) and NPM install &/or worker deploy
    j

    jubu02

    01/05/2024, 2:16 PM
    I'm trying to setup a worker with separate /path functions as separate files just like the router/proxy template. However, I need to be able to install NPM packages to one or some of these separate worker scripts.. that seems impossible, since I cannot do it from the Web Code Editor nor can I work with multiple files in Wrangler, it can only handle one per folder? Is this not possible??
    c
    • 2
    • 13
  • Is it possible to get Wrangler to reference source file names, not compiled ones, when error'ing?
    m

    mitya2364

    01/05/2024, 6:26 PM
    See screenshot. This makes it quite hard to debug since I don't know what file the error happens in as it references compiled files (e.g.
    /.wrangler/tmp/dev-BjjrCX/index.js
    not
    my/original/file.js
    ). Thanks.
    c
    • 2
    • 9
  • Wrangler is throwing "connection terminated unexpectedly" errors for my Postgres DB
    m

    mitya2364

    01/05/2024, 6:51 PM
    I have an [ongoing issue](https://discord.com/channels/595317990191398933/1185199329317765231) with Wrangler being weird about connecting to DBs from my machine. Today I've started getting
    Error: Connection terminated unexpectedly
    from Postgres. This only happens when using the DB within Wrangler. I have another, non-Wrangler app that connects to the same DB in the same way and via the same connection string, and it's fine. The DB is up, and showing no signs of issues. Here's the util my controllers call to connect to and run a query on my DB:
    Copy code
    export const query = async (q, params) => {
        const client = new Client({
    connectionString: env[env.DB+'-db'].connectionString,
            ssl: {rejectUnauthorized: false}
        });
        await client.connect();
        const res = await client.query(q, params);
        return res;
    };
    The DB connection string is in my TOML under
    [[Hyperdrive]]
    . If I
    console.log(client)
    right after connecting, it shows
    readyForQuery: true
    . But when I then run a query, I get this error. Sorry if this is not related to Wrangler but as I say, it's not happening in non-Wrangler setups with the same DB connection code. Any idea what might be up?
    j
    • 2
    • 2
  • how to create amp html in r2 cloud flare
    r

    rinal_43161

    01/05/2024, 7:06 PM
    please help me for this @anyone
    c
    • 2
    • 1
  • Workers Custom Domain issue
    h

    herwork

    01/05/2024, 9:19 PM
    My issue is that I have a worker setup on my account on Cloudflare. But I want to use a domain which my account do not own. But I do have full domain administrator access and Domain DNS access.
    c
    • 2
    • 15
  • wrangler entrypoint errors
    k

    KTibow

    01/07/2024, 12:07 AM
    why? how?
    k
    • 2
    • 4
  • Unable to access worker pages in Dashboard
    s

    saraikium

    01/07/2024, 5:36 AM
    I'm unable to click on any worker related product pages inside my dashboard. In the sub-navigation of workers, I can only click on the plans page. If I click on KV, Queues, D1 or HyperDriver, it redirects me to the overview page. Can someone kindly help me figure out what's happening here? I'm a first time cloudflare user and this is very frustrating to be honest.
  • "Failed to register worker in local service registry TypeError" problem
    b

    bbg0x

    01/07/2024, 4:28 PM
    Greetings, Every time I run my cloudflare worker application, which I created from scratch today, I keep getting this error. I deleted it and created it again, but I couldn't solve the error and I couldn't find a solution for it. If anyone has this problem or knows the solution, I would appreciate if you could help me. Thank you.
  • Custom Markdoc's components work on local with wrangler but fail online with Pages
    r

    rodbs

    01/07/2024, 4:31 PM
    I've create a custom Markdoc components following this guide: https://markdoc.dev/docs/examples/react In local, the component (Counter) works ok, and when consologing you get this:
    Copy code
    {
          '$$mdtype': 'Tag',
          name: 'Counter',
          attributes: [Object],
          children: []
        }
    But on deploying to Pages I get an error
    Copy code
    Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
    and the console:
    Copy code
    {
          '$$mdtype': 'Tag',
          name: '_R',
          attributes: [Object],
          children: []
        }
    So it's like the render is working locally and not online. I've spotted the 'rendering error' in the
    transform
    method:
    Copy code
    const ast = parse(markdown) 
    const config = {
            tags: { counter, },
           
        }
        return transform(ast, config)
    `
    What else can I do to debug it? Is the bug in Worker backend?? (because Markdoc works ok locally)
    • 1
    • 1
  • Max Queries per second for DO
    s

    s.x.m

    01/07/2024, 6:22 PM
    In docs there is soft limit mentioned of 1000 queries per second per durable object. My question is, if I have class Page, and I create DO with .idFromName(pathname) , does it mean that each different path will get 1k queries per second limit? Or whole Page class gets 1k regardless of
    pathname
    ?
    k
    • 2
    • 2
1...678910Latest