Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS public environment variable not working on Azure App Service

I have a NEXT_PUBLIC environment variable in my NextJS application. It has been set in my .env.local file and working correctly but after it has been deployed to Azure App Service the app is unable to read it. It is 'undefined'. I have configured it under Configuration for the App Service.enter image description here

Any advice on what the issue might be?

Thanks in advance.

like image 437
Gericke Avatar asked Dec 18 '25 16:12

Gericke


1 Answers

I had the same problem that the NEXT_PUBLIC environment variables on my Azure AppService always had the value "undefined", although they were defined as environment variables in the AppService settings.

When building the Docker image, the NEXT_PUBLIC environment variables are set directly during the build and cannot be overwritten afterwards. This was the reason why the settings from the AppService for the NEXT_PUBLIC did not work.

The following solution by Renato Pozzi (dev.to) helped me.

Here are my steps: (next v.12.2.5):

a) Create the desired NEXT_PUBLIC variable in the Dockerfile before the "build" process start and fill it with a "placeholder value".

RUN NEXT_PUBLIC_API_URL=PLACEHOLDER_NEXT_PUBLIC_API_URL yarn build

b) Create an entrypoint file (entrypoint.sh) which replaces the placeholder value with real environment variables from the AppService when the Docker image start.

In my example, the placeholder "PLACEHOLDER_NEXT_PUBLIC_API_URL" is replaced with the real value "NEXT_PUBLIC_API_URL" from the AppService configurations (environment variables).

#!/bin/sh
test -n "$NEXT_PUBLIC_API_URL"
find /app/.next \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i "s#PLACEHOLDER_NEXT_PUBLIC_API_URL#$NEXT_PUBLIC_API_URL#g"
exec "$@"

c) Make the previously created entry point file known in the Dockerfile.

COPY --chown=nextjs:nodejs entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["node", "server.js"]
like image 108
Paul Franke Avatar answered Dec 21 '25 07:12

Paul Franke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!