How to access env variables in shopify hydrogen?

491 views Asked by At

`

These variables are only available locally in MiniOxygen

SESSION_SECRET="foobar"
PUBLIC_STOREFRONT_API_TOKEN="3b580e70970c4528da70c98e097c2fa0"
PUBLIC_STORE_DOMAIN="hydrogen-preview.myshopify.com"

`

i have this .env file in root of my project(created by npm create @shopify/hydrogen@latest)

How to access variables in this .env file? For example i have config

config.ts

`
const builderHost = 'https://example.com';

const Config = {
  apiKey: process.env.API_KEY ?? '',
  builderWelcomeUrl: `${builderHost}/share/xxxxxxx`,
};
export default Config;

` (also i added API_KEY variable in .env file)

process.env.API_KEY ----> I gain this error: ReferenceError: process is not defined

I'm trying to get API_KEY from .env, write it to config.ts file and use it in my app

I want to write API_KEY in my config.ts file and use it in my app

1

There are 1 answers

0
Nirav Jethva On

If you want to access your public environment variables outside component scope, you may do this like this on root loader:

export async function loader() {
  return json({
    ENV: {
      API_KEY: process.env.API_KEY,
    },
  });
}

export function Root() {
  const data = useLoaderData<typeof loader>();
  return (
    <html lang="en">
      <head>
        <Meta />
        <Links />
      </head>
      <body>
        <Outlet />
        <script
          dangerouslySetInnerHTML={{
            __html: `window.ENV = ${JSON.stringify(data.ENV)}`,
          }}
        />
        <Scripts />
      </body>
    </html>
  );
}

Now in your config.ts file you may update like this:

const ENV =
  typeof document !== "undefined" && typeof window !== "undefined" && window?.ENV
    ? window.ENV
    : {};

const config = {
  apiKey: ENV.API_KEY ?? "",
};

export default config;

Reference: Environment Variables