1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This will be exposed to users. if I want to load it in my pages I need to put them in env.local?
@ashes999 Using .env file should work as well. I've also updated answer with more information

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.