Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS - How to get runtime environment variables

Noob question, my apologies.

I'm wondering if anyone knows the recommended deployment flow for NextJS self-hosted (e.g. docker or kubernetes). I'm doing a typical build once, ship per environment while changing environment variables to match the environment but keeping the image the same.

Since NextJS auto-opts-out of SSG when you use "getInitialProps" and "publicRuntimeConfig", I'm wondering, what's the best way to deploy the same image to multiple environments (again, self hosted on generic cloud e.g. docker run).

  1. Do I have to always bake in the environment variables? So I have to build an image per environment, and per update to env vars.
  2. Use publicRuntimeConfig / getInitialProps but forget about SSG optimisation, even if my variables are non-sensitive (e.g. GA_TRACKING_ID)
  3. ... Is there anything else?

Thanks for your help!

like image 795
Bo Ogunlana Avatar asked Nov 26 '22 13:11

Bo Ogunlana


1 Answers

You might want to check out react-env which does just that.

The idea is that react-env will generate for you an __ENV.js JS file with your environment variables, which you can then access on client side via the window or via the env helper, eg:

<small>
  Works in the browser: <b>{env("CRA")}</b>.
</small>

When using Docker, you may set an entrypoint that generates the required __ENV.js when the container boots:

ENTRYPOINT yarn react-env --env APP_ENV
like image 137
Gyum Fox Avatar answered Dec 04 '22 06:12

Gyum Fox