How to access ENV variables on client side with NextJS

Hello guys

We have some env variables setup in edg Environments | Edgio Documentation

We can access those at the build time. How can be get those env also at client side with NextJS? This is more of NextJS issue for sure :slight_smile:

Thanks

How about edg env pull my-file.env?

I think that could work. In edgio console, defined env variable like this:

NEXT_PUBLIC_ANALYTICS_ID

And then add to the build process, before running the actual build

edg env pull .env.production

As per Basic Features: Environment Variables | Next.js

I wonder if maybe just naming the variable and than running the build might work just like that

1 Like

If I understand the ask correctly, so long as the env vars are prefixed with NEXT_PUBLIC_, then you can use them on the client with process.env.NEXT_PUBLIC_XYZ.

Now if they are defined in Edgio console, you will need to do edg env pull ... as you referenced to bring them local for building/local dev.

1 Like

The problem is when browser tries to make the request and tries to access the ENV var passed from server, it is being shown undefined. This is breaking the application. When app, makes server side request, it works fine as the env vars are available via process.env.VAR_NAME but its not available to the browser.

I’ve successfully accessed them during build time, which is fantastic. But now, I’m scratching my head on how to get those very same environment variables on the client side of my Next.js application. I sense this is more of a Next.js challenge than an EDG one. Any guidance on how to make these Edge Environment variables accessible to the client side of my Next.js app would be highly appreciated.