next-on-pages process.env values are undefined

Hey! I was wondering if anyone has faced an issue where process.env values, such as process.env.NEXT_PUBLIC_API_URL is coming through as undefined on build? Both on deploy and preview with pages. In standard next development mode it works fine. I tried a normal next static export and serving that on a simple server, and that works fine. So somewhere in the cf build process I seem to be losing these values. I’m not using any of the cf services directly in this pages app, all that happens on a standalone worker (which is the api url im trying to connect to). This only happened when I migrated my code over to cloudflare from render. They were both set up nearly identically, with the env values being set in the environment variables section of the dashboard. As a sanity check I also tried moving my logic into a clean vite app, which also worked with the vite env syntax. Am i misunderstanding something basic about how cloudflare handles env values? I do not have a wrangler.toml for this next app, everything is handled in the repo and the environment variables in dashboard and a .env file locally. Any help would be appreciated, thank you!
1 Reply
b1ueh4wk
b1ueh4wk2w ago
I am running into the same issue. I know that this isn't the most desired function, but at the very entrance of your application, can you console.log the process object? and can you console.log the process.env object? I was able to access the process.env on my front-end application using console.logs, and I was able to find my environment variables. Cloudflare Pages has 2 "environments" Production & Preview; You should define these environment variables for both so if you are testing on the "dev" environment you will still be able to access these. Workers & Pages > YOUR_PAGE > Settings > Choose Environment: > Select Production OR Preview. I was having an issue with my changes to my pages being cached, and when I would push up the changes I realized that my changes were not live (it was still returning the cached previous version). So for a while I thought I couldn't access my process.env because I wasn't getting console.logs. Additionally I would update the keys and cloudflare would have a problem deploying the new keys, so I had to push updates a few times. Console.logs shouldn't remain in the application of course, and any environment variables used in front-end applications will be exposed to your users. Using devtools users will be able to retrieve the tokens and keys to api's.
Want results from more Discord servers?
Add your server