Reputation: 1324
I am trying to get my environment variables in one of my pages, but it is always returning undefined. I have no issues with accessing the variables in api
folder but in pages/page.tsx
it doesn't return the variables.
I access my variables using
const SECRET = process.env.SECRET
from my .env
file.
How can I fix this issue?
Upvotes: 1
Views: 1104
Reputation: 593
I believe the preferred way to implement what you're trying to do is to use env variables on the server side within getServerSideProps()/getStaticProps() methods. This should work as expected without any tricks.
But if you want to access env variables on the client you have to prefix your variable with NEXT_PUBLIC_
Please refer to official docs:
By default all environment variables loaded through .env.local are only available in the Node.js environment, meaning they won't be exposed to the browser.
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_. For example:
NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
Upvotes: 2