DEV Community

Cover image for CloudFlare Workers - some functionality can only be performed while handling a request
Klee Thomas
Klee Thomas

Posted on

4

CloudFlare Workers - some functionality can only be performed while handling a request

Have you encountered this error when trying to upload a CloudFlare Pages function?

Error: Failed to publish your Function. Got error: Uncaught Error: Some functionality, such as asynchronous I/O, timeouts, and generating random values, can only be performed while handling a request.
Enter fullscreen mode Exit fullscreen mode

I ran into it recently when tying to deploy what I thought should be a relatively simple function.

Directions to tell me that the issue was at worker.mjs:11:28 didn't really help me with where to find the issue in my TypeScript code.

Through a process of trial and elimination I ended up finding that it was down to how I was creating Response objects for my error cases.

const errorResponse =  new Response("Error message", {
    status: 400,
  });
Enter fullscreen mode Exit fullscreen mode

I had this at the top level of a module I was importing.

Turns out this is not allowed. Instead I just need to create the responses during the execution of the function by turning the assignment statements in to anonymous factory functions.

const errorResponse = () => new Response("Error message", {
    status: 400,
  });
Enter fullscreen mode Exit fullscreen mode

This keeps the code looking the way I want and CloudFlare is happy to deploy it to a worker.

In retrospect the error message makes sense, but without the context of having solved it I had a really hard time.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (2)

Collapse
 
_hariti profile image
abdellah ht • • Edited

Thanks, You saved me a lot of time!

Collapse
 
irensaltali profile image
İren SALTALI •

Thanks, it really save tons of time here: github.com/irensaltali/serverlessa...

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series