https://discord.cloudflare.com logo
Join Discord
Powered by
# functions
  • j

    James

    03/24/2022, 12:31 AM
    Something like this?
    Copy code
    js
    export async function onRequestGet(request) {
        return new Response(`<h1>Hello world</h1>`, {headers: {'content-type': 'text/html'}});
    }
  • s

    simpson

    03/24/2022, 12:38 AM
    thanks!
  • c

    cojo

    03/24/2022, 3:36 AM
    Hi all, I'm wondering if it's possible (and if not, if it's planned in future) to allow Page Functions to make websocket connections to other servers. I believe the way I am doing this using
    fetch()
    would work with a regular worker (going to try that shortly), but that it is being intercepted in a weird way by wrangler2's
    template-worker.ts
    injected
    fetch
    wrapper that is causing an exception outside of my code's scope. At least, that is what I see locally (calling
    response.status
    here: https://github.com/cloudflare/wrangler2/blob/main/packages/wrangler/pages/functions/template-worker.ts#L112 breaks because I don't have a chance to call
    accept()
    on the
    webSocket
    yet) Another way of phrasing my question might be - am I correct that this template is being used on the actual Cloudflare deployment as well (I tried deploying to Preview to see if maybe this was a local wrangler2 issue only but it is throwing an exception there too)? If so, is there a way I am missing to call
    fetch
    as in the usual Cloudflare worker
    fetch
    instead of this wrapper version? If not, will that change in the future, or do we just have to do any websocket-specific code on a separate worker env from the rest of our Page setup? Thanks in advance!
  • c

    cojo

    03/24/2022, 4:13 AM
    here's the error log in case it's helpful (slightly redacted) - you can see here where it is bombing out before it even gives me a chance to run the
    .accept()
    call (which I do have in there immediately; just not getting that far...):
    Copy code
    [pages:err] POST /api/admin/testSig: TypeError: Cannot read properties of undefined (reading 'status')
        at next (....../node_modules/wrangler/pages/functions/template-worker.ts:112:50)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at EventTarget.[kDispatchFetch] (....../node_modules/@miniflare/core/src/standards/event.ts:359:13)
        at Server.<anonymous> (....../node_modules/@miniflare/http-server/src/index.ts:168:20)
    POST /api/admin/testSig 500 Internal Server Error (610.90ms)
    ......./node_modules/wrangler/wrangler-dist/cli.js:48070
                throw ex;
                ^
    
    TypeError: You must call accept() on this WebSocket before sending messages.
        at EventTarget.[kClose] (......./node_modules/@miniflare/web-sockets/src/websocket.ts:164:13)
        at WebSocket.<anonymous> (......./node_modules/@miniflare/web-sockets/src/couple.ts:36:30)
    ...
        at WebSocket.emitClose (......../node_modules/@miniflare/web-sockets/node_modules/ws/lib/websocket.js:247:12)
    ...
        at processTicksAndRejections (node:internal/process/task_queues:82:21)
  • c

    cojo

    03/24/2022, 4:14 AM
    this results from calling:
    Copy code
    fetch(this.address, {
          headers: { Upgrade: 'websocket' },
        })
          .then((resp) => {
            console.log('Using our connect override!');
    and we never get to that log.
  • b

    boojum

    03/25/2022, 8:02 AM
    Hey there! Is it possible to have a function living at the root of the site (so
    functions/index.js
    ) and taking an action before serving the actual site? For example, redirecting somewhere else based on some condition. It seem like it should be possible but I can't figure this one out. The - not working! - explanation in code:
    Copy code
    js
    // i live at functions/index.js
    const destinationURL = 'https://startpage.com'
    const statusCode = 301
    
    export async function onRequest(context) {
      const { request } = context
    
      const url = new URL(request.url)
    
      if (url.pathname.startsWith('/test')) {
        return Response.redirect(destinationURL, statusCode)
      }
    
      return Response
    }
  • b

    boojum

    03/25/2022, 8:47 AM
    Issue solved with help of @jwagner, over at CLoudflare community. For those interested: https://community.cloudflare.com/t/using-function-as-a-proxy/372133
  • r

    Rhino233

    03/25/2022, 7:22 PM
    Hi, is there a way to debug CF functions. I've just written a test interceptor for one of get request like export async function onRequestGet({ request, params, env }) { return new Response('hello world'); } but it has no effect on the request I made on the page. And I can confirm the build picked up the function file I defined in the "Functions" tab
  • i

    Isaac McFadyen | YYZ01

    03/25/2022, 7:26 PM
    Unfortunately Functions don't yet have logs. I'd suggest using something like wrangler2 to debug them locally.
  • r

    Rhino233

    03/25/2022, 7:28 PM
    for that I think I can send logs to external service like Datadog or something. The problem right now is seems the functions is not invoked. Not sure what next step I can take to debug it
  • r

    Rhino233

    03/25/2022, 7:28 PM
    Also thanks for replying!
  • r

    Rhino233

    03/25/2022, 7:30 PM
    btw, I think it used to be working a few months ago, we enabled bot prevention recently, not sure if it could be related
  • s

    solidny

    03/26/2022, 2:49 PM
    Hi, is it possible to add a binding of a env variable defined in Pages "Environment variables->Preview" UI panel to a local dev env started with wrangler? I have a few secrets defined in there and I don't want to have them explicitly stored in the repo (e.g. as a package.json custom script) just so that I can run the function on a local environment
  • z

    Zottelchen🍭

    03/26/2022, 4:50 PM
    Am I right in my assumption that if I want to save a weekly auth_token from an API that I should use KV to do that?
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 4:56 PM
    Yup, that's correct.
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 4:57 PM
    KV is eventually consistent so changes might take up to 60 seconds to propagate but you don't care if it's weekly.
  • z

    Zottelchen🍭

    03/26/2022, 5:01 PM
    So KV is basically shared env-vars while writing to env directly would be specific to that worker, right?
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 5:01 PM
    Yeah, and you can't change environment variables at runtime.
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 5:01 PM
    So there's no way to save an auth token from the Worker itself with env variables.
  • z

    Zottelchen🍭

    03/26/2022, 5:01 PM
    Okay, thanks 🙂
  • j

    john.spurlock

    03/26/2022, 5:27 PM
    How does pages functions work under the hood? Let's start with the functions folder approach (ie not advanced mode). I declare a few .ts files and git push. Does CF compile/build these on their build servers during the pages build? What tool/bundler does it use to do it? How are imports handled / what ts syntax is supported? Does it create a single "normal worker" from the output of this process? How are the assets deployed? (KV?) Can I tail the console logs of the resulting worker?
  • j

    James

    03/26/2022, 5:33 PM
    npx wrangler pages functions build
    is effectively what's run I believe to generate the resulting worker if you want to take a look at the result - it uses esbuild if I recall correctly. It's all open source at https://github.com/cloudflare/wrangler2 if you want to go digging. Assets for Pages are stored in KV behind the scenes, yeah. I see @User typing so he might have more specifics 👀
  • w

    Walshy | Pages

    03/26/2022, 5:34 PM
    1. Yes we build it during the build 2. It's using esbuild 3. Whatever is being supported by your settings 4. Yes, it becomes a single worker 5. Secret 😉 (KV) 6. Not yet, it's on the roadmap.
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 5:34 PM
    5. is the reason for the asset size limitation FYI.
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 5:35 PM
    It's not just random 😄
  • j

    john.spurlock

    03/26/2022, 5:46 PM
    Nice, thanks - can you elaborate on: "3. Whatever is being supported by your settings". which version of esbuild is used, and how does one configure it? Again in the static .ts files in the functions folder scenario.
  • i

    Isaac McFadyen | YYZ01

    03/26/2022, 6:01 PM
    AFAIK there's no way to override
    esbuild
    settings for Functions yet unfortunately (although Walshy is welcome to refute that haha)
  • j

    john.spurlock

    03/26/2022, 7:24 PM
    That's unfortunate - I guess I'll hunt around in the wrangler2 source for what's used today
  • w

    Walshy | Pages

    03/26/2022, 7:26 PM
    Yeah I should clarify, I was talking about like NODE_VERSION You can't modify the esbuild settings or bundler. For that we recommend using
    _worker.js
    . Good shout by Isaac on checking wrangler2, that should match what we do today
  • j

    john.spurlock

    03/26/2022, 9:06 PM
    It would be good to document which esbuild version, and under what tsconfig it runs (on the build server), also under what typescript version it runs. The local build for wrangler2 is currently using esbuild
    0.14.23
    - but it's unclear if
    buildWorker
    (https://github.com/cloudflare/wrangler2/blob/7e8ec9a0807deacd58cd25f5a8fd7d21b2fdb535/packages/wrangler/pages/functions/buildWorker.ts#L14) also runs on the build server to produce the worker used for deployment
1...108109110...392Latest