2

I've done a Node JS server with ES6 using import and export, but when I want to access to an enviroment variables to print that, they return me "undefined". This is my code :

import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import 'babel-polyfill'
import userRoutes from './routes/user.routes.js'
import db from './db/database.js'
import dotenv from 'dotenv'

dotenv.config()

const PORT = process.env.PORT || 5001
const app = express()
db.connection()

app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors())

app.use(userRoutes)

app.get('/', (req, res) => {
  res.send('Hello world')
})
app.listen(PORT, () => {console.log(`Server on port ${process.env.PORT} and secret key ${process.env.JWT_KEY}`)})
ricmiber96
  • 21
  • 3

2 Answers2

0

Only thing I can think of is your .env file not being in root folder.

move your .env file to root folder and your environment variables should be loaded to your application.

otejiri
  • 1,017
  • 6
  • 20
Furqan Ali
  • 11
  • 1
0

If your .env file is not in the root of your project you can manually set it's path via this code :

const path = require('path')

require('dotenv').config({ path: path.resolve(__dirname, '../.env') })
Moein Moeinnia
  • 1,945
  • 3
  • 10
  • 26