strapi/nextjs-corporate-starter

TODO: Suggestion: Remove NEXT_PUBLIC Prefix for API Keys in .env File

Yaren-IT opened this issue · 2 comments

Problem

The current documentation suggests prefixing API keys with NEXT_PUBLIC for environment variables in Next.js applications. However, this could potentially lead to security vulnerabilities as these keys may inadvertently be exposed to the client side.

Solution

The official Next.js documentation source recommends not using the NEXT_PUBLIC prefix for sensitive environment variables, such as API keys. By removing the prefix, these variables remain private and can only be accessed on the server, minimizing the risk of unintentional client-side exposure.

Reference

Next.js documentation advises against using the NEXT_PUBLIC prefix for sensitive environment variables:

"Since the environment variable API_KEY is not prefixed with NEXT_PUBLIC, it's a private variable that can only be accessed on the server. To prevent your environment variables from being leaked to the client, Next.js replaces private environment variables with an empty string."

After changing my .env file, to change all of the variables in the code, I've used following command in Linux bash:

cd frontend/src/app
for i in $(grep -rl NEXT_PUBLIC) ; do sed -i -E 's/NEXT_PUBLIC_([A-Z_]+)/\1/g' $i ; done 

@Yaren-IT I think this would be a good change. When I initially build this I did not mind keeping NEXT_PUBLIC and it made the variable accessible client side. But this would be a good refactor to do. I would add it to my todo, but if you would like to make a PR before than. Feel free to do so.

Just have to check, that where ever we are using none NEXT_PUBLIC env we will have to refactor some logic to run the code server side. Because I believe we wont be able to access those variables client side.