vite-plugin-cloudflare icon indicating copy to clipboard operation
vite-plugin-cloudflare copied to clipboard

Having problem accessing environment variables within worker/index.js

Open sergor5 opened this issue 11 months ago • 4 comments

With this example below I was unable to get the environment variable by:

  • process.env.DEBUG
  • import.meta.env.DEBUG
  • tried cross-env or dotenv
import { endianness } from 'os';
// just to check if polyfilledModules work
import util from 'util';
import { handleStaticAssets } from './static-assets';

const DEBUG = false; //set to TRUE when running in dev mode

addEventListener('fetch', async (event) => {
    const { pathname } = new URL(event.request.url);
    if (pathname.startsWith('/api')) {
        event.respondWith(handleRequest(event.request));
        return;
    }

    if (DEBUG) {
        // we skip miniflare and let vite handle the url
        event.respondWith(new Response('', { headers: { 'x-skip-request': '' } }));
    } else {
        // this will disable HMR in vite, so only for production
        event.respondWith(handleStaticAssets(event));
    }
});

async function handleRequest() {
    util;
    const obj = {
        __dirname: __dirname,
        __filename: __filename,
        cwd: process.cwd(),
        global: !!global,
        Buffer: !!globalThis.Buffer,
        process: !!process,
        endianness: !!endianness,
    };
    return new Response(JSON.stringify(obj));
}

Is there a way for that?

sergor5 avatar Jul 11 '23 08:07 sergor5