How can I be absolutely sure my environment variables aren't exposed to the client?
Unanswered
Bumble bee posted this in #help-forum
Bumble beeOP
I came across this post and it kinda scared me: https://github.com/vercel/next.js/discussions/23980
the only places i reference my environment variables are in a utils file and this is only called in server components/server actions. is this enough? do i need "use server" at the top of the utils file?
the only places i reference my environment variables are in a utils file and this is only called in server components/server actions. is this enough? do i need "use server" at the top of the utils file?
9 Replies
Komondor
I'm not sure about the flickering in the example you posted, but having env variables available in a statically rendered page that gets rendered on the server seems like expected behavior.
That doesn't mean your environment variables are exposed to the client. It means you can build a webpage like <div>{process.env.MONGODB_URI}</div> and NextJS will compile that on the server and then serve it as a static web page
That doesn't mean your environment variables are exposed to the client. It means you can build a webpage like <div>{process.env.MONGODB_URI}</div> and NextJS will compile that on the server and then serve it as a static web page
Komondor
Actually I was able to reproduce the flickering thing like this
import ClientComponent from "./clientComponent"
export default async function Page() {
return <ClientComponent />;
}'use client'
export default function ClientComponent() {
return <div>{process.env.MONGODB_URI}</div>;
}but that doesn't mean all of the environment variables get sent to the client, the environment variable was expanded out into the component on the server
It even mentions it in the hydration error, that it did not expect the server html to contain the text
Now when I change my env variable from MONGODB_URI to NEXT_PUBLIC_MONGODB_URI I no longer get the hydration error because it is available to be used on the client.
But still, all of my env variables are not getting shipped down to the client
But still, all of my env variables are not getting shipped down to the client
It's okay to use environment variables on the server (we use them to connect to databases). Just don't put your private env variables into divs and render them otherwise the client will see them
if you add
you can also scan the build output of
import "server-only"; to the top of your utils file then you can ensure it's only ever called on the server. it'll error at build time if that's not the case.you can also scan the build output of
.vercel/output with a tool like https://github.com/trufflesecurity/trufflehog to detect any secrets in the output. I wrote a blog post about how to do this in GitHub Actions at https://blog.arcjet.com/secret-scanning-and-next-js-builds/Bumble beeOP
@Komondor @davidmytton thank you for the detailed responses!
and I will check out the blog post :)