next-on-pages icon indicating copy to clipboard operation
next-on-pages copied to clipboard

[🐛 Bug]: Setting NEXT_PUBLIC_ during preview build

Open seivad opened this issue 1 year ago • 2 comments

next-on-pages environment related information

Latest

Description

Is there a way to set NEXT_PUBLIC_BASE_URL for example with the dynamically generated url provided during pnpm run deploy?

I cannot figure it out and there are actions in my NextJS project that look for process.env.NEXT_PUBLIC_BASE_URL but because I have 1 or more items set in wranger.toml, I cannot adjust on the web interface.

I know there is CF_PAGES_URL during build but there are no instructions on how to set this in wrangler.toml as a [vars] item, any help is greatly appreciated to get past this blocker.

Reproduction

No response

Pages Deployment Method

Direct Upload (wrangler pages publish or the @cloudflare/pages-action GitHub Action)

Pages Deployment ID

No response

Additional Information

No response

Would you like to help?

  • [X] Would you like to help fixing this bug?

seivad avatar Apr 26 '24 04:04 seivad

Hi @seivad 👋 (so sorry for the very late reply! 🙇)

The CF_PAGES_URL environment variable is injected in your application during deployment (as per the pages docs) and it is then always available in your deployed application and you can simply use it via process.env or getRequestContext.

I've created this minimal demo for you on how you could use this variable (alongside the other Pages injected ones) while also having the variables populated during local development (via .dev.vars): https://github.com/dario-piotrowicz/next-on-pages-cf-pages-envs-demo.

I hope this helps, please let me know if it does 🙂

[!NOTE] You do now want to set the CF_PAGES_URL in your wrangler.toml file as it would override the injected variable, so either make the variable optional and check for its existence or use the .dev.vars file like in my demo

dario-piotrowicz avatar May 19 '24 16:05 dario-piotrowicz

@dario-piotrowicz I have an app with a .env file containing mostly public variables (no secrets), as shown below:

.env
NEXT_PUBLIC_XXX_SERVICE_URL=https://xxx.xxxx.workers.dev
NEXT_PUBLIC_YYY_SERVICE_URL=https://yyyy.xxx.workers.dev

As far as I know, prepending NEXT_PUBLIC_... makes these variables accessible via process.env.VARIABLE. This works correctly for me. However, when I deployed the app to Cloudflare Workers, it functioned as expected initially. But when I change any of these variables in the .env file and redeploy, the app continues to use the old variable values instead of the updated ones.

Do you have any idea how to resolve this issue or what I might be doing wrong?

Note: I do see the updated values in the .vercel/output/functions.

KamaniBhavin avatar Jun 05 '24 04:06 KamaniBhavin