Yihan Duan
Yihan Duan

Reputation: 43

WIll .env File Variables be exposed to Users in Nextjs?

I am building a webapp using nextjs. I added some dependencies like Mux and Firestore. In order to store api_keys and others in an organized way, I created .env file and put it in the root directory.

I checked the rules for .env in nextjs. Here is the reference: https://medium.com/courtly-intrepid/environmental-variables-in-next-js-with-dotenv-599c5bbfdf74. I added NEXT_PUBLIC prefix for variables, then they were resolved successfully.

However, after checking the nextjs official docs https://nextjs.org/docs/basic-features/environment-variables, it says the variables will be exposed to browser. I feel confused about browser. Does it mean if a user use his/her browser to use my app, my enviroment varibles will also be exposed to him/her?

One thing I was thinking, if I put all codes that need dotenv into backend side, Can I make these variables not to users? For current version, I used dotenv in the components which, I think, might cause varibles seen by frontend users? Screenshot of code in Component which needs dotenv

P.S.: I am new here. I don't have enough reputation to show your screenshot directly. The link is used instead.

Upvotes: 2

Views: 1742

Answers (1)

I recommend you to use NEXT_PUBLIC prefix, but if you want that your variables mantain 100% isolated from frontend, you could do this:

Create and .env file:

TOKEN = 45354354353

next.config.js file:

module.exports = {
  env: {
    TOKEN: process.env.TOKEN,
  },
};

Upvotes: 5

Related Questions