简体   繁体   中英

Environment Variables undefined NextJS

I want to set a simple login with just a password in.env but when I try to use this variable it takes undefined.

Code:

.env.local

REACT_APP_PASS_TOKEN=d61b100cacb60432f97b39b70d9ff5067242a5d9da1acad54738fc65562b8e1b

login.js

(First log prints value correctly but second one does not)

const pass = process.env.REACT_APP_PASS_TOKEN


console.log(`KEY: ${pass}`)

const handleLogin = () => {
    console.log(`KEY: ${pass}`)
  }

You need some mechanism to manage this process. Try with dotenv. Simply install this using

npm i dotenv

After that you need to attach this module to your main app.

require('dotenv').config();

Try to define variable and assign API key to it.

const psw = process.env.REACT_APP_PASS_TOKEN;

Then just swap var names. In result should to looks like:

.env

REACT_APP_PASS_TOKEN=d61b100cacb60432f97b39b70d9ff5067242a5d9da1acad54738fc65562b8e1b

login.js

const pass = process.env.REACT_APP_PASS_TOKEN;
require("dotenv").config();

const psw = process.env.REACT_APP_PASS_TOKEN;

console.log(`KEY: ${psw}`);

const handleLogin = () => {
  console.log(`KEY: ${psw}`);
};

handleLogin();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM