Environment variable is exposed to the browser
Unanswered
Alaska pollock posted this in #help-forum
Alaska pollockOP
I want to hide my environment variable from the browser so it shows up as undefined in the source code.
32 Replies
prefix your env with
NEXT_PUBLIC_Alaska pollockOP
does that hide it from the browser?
still doesn't work
@Alaska pollock I want to hide my environment variable from the browser so it shows up as undefined in the source code.
if the env var is not prefixed with
NEXT_PUBLIC then it will not be sent to the browser@joulev if the env var is *not* prefixed with `NEXT_PUBLIC` then it will not be sent to the browser
Alaska pollockOP
i understand that, but it still does get sent to the browser, even thought it'snot prefixed with NEXT_PUBLIC. i don't know why
@Alaska pollock i understand that, but it still does get sent to the browser, even thought it'snot prefixed with NEXT_PUBLIC. i don't know why
how can you confirm it is sent to the browser?
Alaska pollockOP
give me a second
here is my code
here is the source code in the browser when you press f12
@Alaska pollock Click to see attachment
the reason is that you are rendering it in a server component which can access the env var
Alaska pollockOP
so i need to render it as client?
it is like
export default async function Page() {
const secret = await getSecret();
return <div>{secret}</div>; // whoops
}but the script needs that id to work
if you dont send that to the browser how does the script know what id to use?
Alaska pollockOP
this should fix the problem then rigth?
@Alaska pollock this should fix the problem then rigth?
then it will just be
https://www.googletagmanager.com/gtag/js?id=undefinedif it works for you then that's fine
but it most likely won't send any analytics for you
Alaska pollockOP
what do you suggest i change then?
@joulev but it most likely won't send any analytics for you
Alaska pollockOP
you're right, it won't
@Alaska pollock what do you suggest i change then?
nothing, prefix
NEXT_PUBLIC to the variable and expose it to the client because it is not a secretgoogle analytics needs that id to identify your app
Asian black bear
Doesn't it just work as a server component without renaming the environment variable or anything?
@Asian black bear Doesn't it just work as a server component without renaming the environment variable or anything?
it does work as a server component, but it's good practice to name it with
NEXT_PUBLIC if you are fine with it being exposed to the browserso the next maintainer won't be confused when seeing why a supposedly secret env var is exposed
no need to delete your message, that is a good advice
to replicate what minabot suggested, don't put
use client here because it isn't necessaryuse
NEXT_PUBLIC + server component@joulev use `NEXT_PUBLIC` + server component
Alaska pollockOP
appreciate the help. I will do that