I have a file which connects to Contentful
using my specific space
and accessToken
. Recently, I decided to hide the keys
into an .env
file using the dotenv
package. This is what my file looks like:
import {createClient} from 'contentful';
require('dotenv').config();
//console.log('space = ', process.env.CONTENTFUL_SPACE);
const client = createClient({
space: process.env.CONTENTFUL_SPACE,
accessToken: process.env.CONTENTFUL_TOKEN
});
export default client;
For some reason, the env
variables are coming out as undefined. Currently, my .env
file is under the root dir. This is the file structure of my project:
project
client
src
service
client.js <-- The file I pasted above
node_modules
.env
package-lock.json
package.json
Things I've tried:
dotenv
and reinstalled itnode_modules
folder and reinstalled all dependencies.env
file under service
folder where the client
file existsREACT_APP_*
prefix for my env variables in .env
fileconfig
callAll of these solutions came from other stackoverflow
questions. I've been stuck on this for a few days circling through the solutions listed and looking for others but still haven't figured out why I'm not able to access my env
variables!
So I tried structuring a sample project the same way you've structured it, and it didn't work. I moved the.env file under /service folder, it worked. My guess is, requiring the dot env file should be on the main file that wraps your project (main file in the root), along with.env file.
Try setting a path to your.env file in the config.
const dotenv = require('dotenv');
dotenv.config({ path: '../../../.env' });
edit: config path
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.