I will expand on @gyum-fox answer, because react-env
docs wasn't up to date and couple of things took some time to figure out.
Next.js version: 12.2.5
Packages
In react-env
Next.js repo were used 2 packages: react-env
and @beam-australia/react-env
. I don't know what's the purpose of the former, I used the latter.
"Isomorphic"
react-env
claims it's isomorphic, but I can't manage to make it work server side. So here comes the changes to .env file
REGULAR_VAR=VALUE
NEXT_PUBLIC_REGULAR_VAR=$REGULAR_VAR
Some variables I used both on server and client, so to make it work:
REGULAR_VAR
was used on server, manages in .env
file
NEXT_PUBLIC_REGULAR_VAR
was used on client like this: env('REGULAR_VAR')
(note: NEXT_PUBLIC
prefix was removed). Manages in __ENV.js
file
Using the package
To use __ENV.js
file in Next.js, place the following line in _document.tsx
<Script src="/__ENV.js" strategy="beforeInteractive" />
Note: while __ENV.js
sits in /public
directory, at run-time file will be in root, as every file of that directory will be
Generating __ENV.js
file
react-env
command only needed to generate __ENV.js
, so you can launch project:
# like this
npx react-env --prefix NEXT_PUBLIC -- node server.js
# or like this
yarn react-env --prefix NEXT_PUBLIC && node server.js
--prefix NEXT_PUBLIC
: NEXT_PUBLIC
is the default for client side env vars
node server.js
: or next dev
or any other command to launch the project
Docker
I use Dockerfile from Vercel example for deployment.
To generate __ENV.js
file in container, change
RUN yarn build
to
RUN npx react-env --prefix NEXT_PUBLIC --path .env.production -- yarn build
Here, I added --path .env.production
to use production env vars.
Conclusion
That's it! Now you can change client env vars in __ENV.js
, restart the
production server and new values will be applied.