I'm working on a project using Cloudflare Workers, Hono, and Bun. I have defined my secret variables in a .dev.vars
file as recommended by the Cloudflare Workers documentation. Here's the content of my .dev.vars
file:
APPWRITE_ENDPOINT=
APPWRITE_PROJECT_ID=
APPWRITE_API_KEY=
My goal is to use these environment variables to configure a client that I want to share across multiple routes in my index.ts
file, without defining the client inside the route handlers.
Here’s a snippet of my index.ts
code:
import { Hono } from "hono";
const app = new Hono();
const client = new Client()
.setEndpoint("") // I want to use APPWRITE_ENDPOINT here
.setProject("") // And APPWRITE_PROJECT_ID here
.setKey(""); // And APPWRITE_API_KEY here
app.get("/users", (c) => {
const users = new Users(client);
const list = users.list();
return c.json(list);
});
export default app;
I want to initialize the client outside of the route handlers so I can reuse it across different routes. My issue is that I'm unsure how to access the environment variables defined in the .dev.vars
file from my code. How can I properly load these environment variables into my index.ts
file and use them to configure the client globally, rather than within each route?
Is there a specific method in Cloudflare Workers or Bun to retrieve these variables?
Thank you in advance for your help!
First load the environment variables using dotenv
import dotenv from 'dotenv';
dotenv.config()
if it doesn't load correctly it's probably because of your file name so you might need to use
.config({ path: [ "./.dev.vars" ] })
Then access them as follows
process.env.APPWRITE_ENDPOINT