0 votes

process.env da undefined usando node/express con typescript

The Problem : I am doing a course where we are using node/express but with typescript, everything has been great, until we started using environment variables, and the steps were simple, install dotenv, then create an .env file inside src, then import dotenv.config(), then use the variables, and it is something I have done multiple times, but, being the first time I try it in typescript, I am getting Undefined

Let me show you the code

introducir la descripción de la imagen aquí

Check that the .env is inside src

.env file

PORT = 5000
NODE_ENV = "development"
JWT_SECRET = "hasdhb66aga36ndghs76sd3"

using the environment variables

import { Request, Response, Router } from "express";
import { validate, isEmpty } from "class-validator";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import cookie from "cookie";
import dotenv from "dotenv";

import { User } from "../entities/User";

dotenv.config();

const login = async (req: Request, res: Response) => {
  const { username, password } = req.body;

  try {
    let errors: any = {};

    if (isEmpty(username)) errors.username = "Username Must Not Be Empty";

    if (isEmpty(password)) errors.password = "Password Must Not Be Empty";

    if (Object.keys(errors).length > 0) {
      return res.status(400).json(errors);
    }

    const user = await User.findOne({ username });
    if (!user) return res.status(404).json({ error: "User Not Found" });

    const passwordMatches = await bcrypt.compare(password, user.password);

    if (!passwordMatches) {
      return res.status(401).json({ password: "Password is incorrect" });
    }

    const token = jwt.sign({ username }, process.env.JWT_SECRET);

    res.set(
      "Set-Cookie",
      cookie.serialize("token", token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "strict",
        maxAge: 3600,
        path: "/"
      })
    );

    return res.json({ user, token });
  } catch (error) {
    console.log(error);
    res.status(500);
    console.log(process.env.JWT_SECRET);
  }
};

As we can see in the last file, I wanted to use console.log to know what happens with the value of my variable and see what the error is, and the console message is as follows

Error: secretOrPrivateKey must have a value
    at Object.module.exports [as sign] (C:\Users\diego cifuentes\Desktop\Studying  Backend\redit\node_modules\jsonwebtoken\sign.js:107:20)
    at C:\Users\diego cifuentes\Desktop\Studying  Backend\redit\src\routes\auth.ts:70:23
    at step (C:\Users\diego cifuentes\Desktop\Studying  Backend\redit\src\routes\auth.ts:33:23)
    at Object.next (C:\Users\diego cifuentes\Desktop\Studying  Backend\redit\src\routes\auth.ts:14:53)
    at fulfilled (C:\Users\diego cifuentes\Desktop\Studying  Backend\redit\src\routes\auth.ts:5:58)
undefined

Objective To Be Achieved : In the last three hours I've tried everything, literally everything and I keep getting undefined, I don't know what the problem really is, I even know that I'm probably asked to try require('dotenv').config(), which didn't work for me. So, if you know any way to help me, I would be grateful, thanks for your time !

0 votes

It seems that you are misplacing the file .env this should be at the root of the project, not in the src

0 votes

Shouldn't it be inside the src folder ? Mmm strange, I thought it should be there Although, after so much time trying to fix that problem, that's probably the mistake here Thanks !

0 votes

Did this work for you?

0voto

DavichoStar Points 16

The file .env is incorrectly located in your folder src should not go there, it should be in the root of your project, next to the package.

You can also define a custom path if you don't want to take it out of the src, you place

import { resolve } from "path";
import { config } from "dotenv";

config({ path: resolve(__dirname, "./.env") });

If it still doesn't work you can try renaming it to .env.local

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X