#How do I access env variables if they secret !?useEnvData()?!

25 messages ยท Page 1 of 1 (latest)

golden kayak
#

How do I access env variables if they secret !?useEnvData()?!

fallen storm
#

up

sterile oyster
#

This lacks information, where and in what environment do you want to access them?

golden kayak
#

Sorry this post its obsolet I think.
I want to access my env values.
I got a .env File on my root and access them in my route (api endpoint) via:

 const { data, error } = await supabase
    .from("User")
    .select()
    .match({ WebsiteId: import.meta.env.VITE_WEBPAGE_ID });

I hope this ist save and the client never sees this env value ๐Ÿ˜„ !

lunar wasp
#

@golden kayak in this way u can pass envs on build time, as far as I get It, so basically values will be included in transplied js. Do u know if there's a way to have envs on runtime? 'cause i'm able to have them via process.env but only on server not on the client.

golden kayak
#

If its just client side you could use a simple static json file?

#

For me the env vars are important for data which shouldnt get visible for the client. If u use env vars on client, the client could see those values ๐Ÿ˜„

#

U know what I mean?

lunar wasp
#

Ok static JSON Is a way, but how to use it when the app Is in a docker container for example? Anyway i got your point regarding the visibility, but aren't visibile as well when u use import.meta.env? I mean they will be bundled but are not uglified...am I right? Maybe i'm missing something ๐Ÿ˜…

frosty warren
#

ENV variable are handled by Vite, so only var starting with VITE_ can be exposed to the client.

lunar wasp
#

Ok so basically what I said, env vars will be bundled during build time.

frosty warren
#

Yes if you opt in for that with the names.

#

For server side secrets I just name them something else and access via Node env instead of vite.

golden kayak
frosty warren
#

It may not always be visible, but as the vite docs https://vitejs.dev/guide/env-and-mode.html says:

To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.

Next Generation Frontend Tooling

#

You can just use process.env.MY_SECRET for node server side code though

golden kayak
coral lion
#

@golden kayak This should get it working and provide insight into server-side and client-side variable visibility.

  1. Add Z_SECRET_KEY="This is the secret key!" to your .env.development file.

  2. Add these lines to your vite.config.ts:

import * as dotenv from 'dotenv';
dotenv.config({ path: "~/secrets/.env.development" });
console.warn(">>>> vite.config.ts - process.env =", process);
  1. Create a test index.tsx:
import { component$ } from '@builder.io/qwik';
import { RequestHandler } from '@builder.io/qwik-city';

export const onRequest: RequestHandler<any> = async (event) => {
    console.warn(`>>>> onRequest - import.meta.env =`, import.meta.env);
    console.warn(">>>> onRequest - process.env =", process.env);
}

export default component$(() => {
    console.warn(`>>>> render - import.meta.env =`, import.meta.env);
    console.warn(">>>> render - process.env =", process.env);
    return (
        <div>
            <button onClick$={() => {
                console.warn(`>>>> click - import.meta.env =`, import.meta.env);
                console.warn(">>>> click - process.env =", process.env);
            }}>Console.log environment vars!</button>
        </div>
    );
});
  1. Run pnpm dev

  2. Search both your console server-side and in the browser client-side for Z_SECRET_KEY. You should only find the secret key on the server-side. Only VITE_ prefixed variables should show up client-side.

Let me know if this helps.

south pumice
#

Can we put this somewhere on the documentation website? It is a really clear example and I'm sure others have the same questions

coral lion
barren sentinel
#

Thanks @coral lion ! great job with showing the example!

I think as this is an topic that relates to both Qwik and Qwik City, it should go in the main Qwik docs
I'd put it under "advanced", maybe after "Custom build directory"
and maybe a possible name could be: "Environment Variables"

**Here's where to add the route - **
https://github.com/BuilderIO/qwik/tree/main/packages/docs/src/routes/docs/advanced

**Here's where to add the link - **
https://github.com/BuilderIO/qwik/blob/main/packages/docs/src/routes/docs/menu.md

Wanna open a qwik PR? (pun intended)

coral lion
orchid carbon
#

I don't think qwik-city should follow the env access method of cloudflare.
This looks reasonable, but code testing will have problems,
and it also affects the creation method of many singleton objects.
In adapters/cloudflare-pages/vite.config.ts, I directly inject all process.env variables into compile-time constants through vite define to solve this problem.

import { cloudflarePagesAdapter } from '@builder.io/qwik-city/adapters/cloudflare-pages/vite'
import { extendConfig } from '@builder.io/qwik-city/vite'
import { config as configDotEnv } from 'dotenv'

import baseConfig from '../../vite.config'

export default extendConfig(baseConfig, () => {
  return {
    define: createEnvVarsDefine(),
    build: {
      ssr: true,
      rollupOptions: {
        input: ['src/entry.cloudflare-pages.tsx', '@qwik-city-plan'],
      },
    },
    plugins: [cloudflarePagesAdapter()],
  }
})

function createEnvVarsDefine(): Record<string, any> {
  configDotEnv({ debug: true })

  const define: Record<string, string> = {}
  Object.keys(process.env).forEach((key) => {
    define['process.env.' + key] = JSON.stringify(process.env[key])
  })
  return define
}
fallen storm
#

is that related with this?

requestEv.env.get("PUBLIC_SUPABASE_URL") ??
      requestEv.platform.env["PUBLIC_SUPABASE_URL"],