Is it possible to run a REST API with a worker?
I've been trying to build a fairly basic API on a worker using the Hono framework.
But I've been hitting wall after wall, mostly with the fact that workers (wrangler) do not work with standard node env variables. I've read the documentation on worker Environment Variables at least 10 time.. but for whatever reason the context of my app design just wont play nice with this way of passing envars Here's My entry point And here's a module that handles connecting to the database Am i just chasing my tail for no reason here? is this something explicitly disabled or prevented on workers? Am i misunderstanding the usecase? would this be better suited on pages? or is this just not something CF intends us to use at all?
But I've been hitting wall after wall, mostly with the fact that workers (wrangler) do not work with standard node env variables. I've read the documentation on worker Environment Variables at least 10 time.. but for whatever reason the context of my app design just wont play nice with this way of passing envars Here's My entry point And here's a module that handles connecting to the database Am i just chasing my tail for no reason here? is this something explicitly disabled or prevented on workers? Am i misunderstanding the usecase? would this be better suited on pages? or is this just not something CF intends us to use at all?
4 Replies
For one, you don't provide a port when running Workers. The second is you shouldn't be initializing the Database Connection in the global scope
Also I don’t think it is possible use mongoose in cf environment
And even if it was, using a DB connection like this in a stateless / serverless runtime is a terrible idea
Environment variables are attached to the request, so you can't access them outside the scope of the request. Like someone else said, creating the database connection in the global scope is not possible due to this. It is also not great to create a long-lasting database connection on workers which are short-lived processes. It is better to make API calls to the database to provide operations.
You've said you already read the environment variable docs, but read this page: https://developers.cloudflare.com/workers/configuration/environment-variables/
The env object is how you access variables (
env.MONGO_URI
in your case) . But that is an argument passed to the request object, so it has to be used within that context.Cloudflare Docs
Environment variables · Cloudflare Workers docs
Environment variables are a type of binding that allow you to attach text strings or JSON values to your Worker