Javascript says that my variables which are in .env are undefined. I’ve installed dotenv but it doesn’t work.
My index.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const router = express.Router();
const port = process.env.PORT || 5000;
const dotenv = require("dotenv");
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');
mongoose.set('strictQuery', false);
dotenv.config();
mongoose
.connect(
process.env.MONGODB_URL
)
.then(() => console.log("Database is working"))
.catch((err) => {
console.log(err)
});
app.use(express.json());
app.use('', authRoute);
app.listen(process.env.PORT, function () {
console.log('Server is up on port ' + process.env.PORT)
})
My auth.js
const router = require('express').Router();
const User = require('../models/user');
const Crypto = require('crypto-js');
const { response } = require('express');
const secretKey = process.env.SECRET_KEY;
// Create a registration
console.log(secretKey);
router.post('/rejestracja', async (req, res)=>{
const nowyUser = new User({
email: req.body.email,
password: Crypto.AES.encrypt(req.body.password, process.env.SECRET_KEY).toString(),
firstName: req.body.firstName,
surname: req.body.surname,
username: req.body.username,
});
try{
const newedUser = await nowyUser.save();
res.status(201).json(newedUser);
}
catch(err){res.status(500).json(err)};
})
// Create a login
router.post('/login', async (req, res) => {
try{
const user = await User.findOne({email: req.body.email});
if (!user) {
return res.status(401).json("i/lub hasło jest nieprawidłowy");
}
const securedPass = Crypto.AES.decrypt( user.password, "a");
const password = securedPass.toString(Crypto.enc.Utf8);
console.log(password);
if (password !== req.body.password) {
res.status(401).json("Email i/lub hasło jest nieprawidłowy");
}else {
res.status(200).json(user);
}
}
catch(err) {
res.status(500).json({message: err.message});
}
});
module.exports = router
And my .env
MONGODB_URL = mongodb+srv://someInterestingWords
PORT = 5500
SEC_KEY = a
Everything works when these variables are in my code, not in .env.
I’ve tried to delete dotenv and add it again but id doesn’t change anything.
process.env.something works in index.js but it doesn’t in other files


