Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

295
Vistas
Loading environment variables with dotenv still returns undefined

I'm at a loss here. My .env file is in my root directory, as instructed. I've tried this by way of both require('dotenv').config() and import dotenv from 'dotenv', followed by dotenv.config(). I've tried passing config an absolute path, as you will see. Trying to console log the environment variables always returns undefined. I tried checking for dotenv.error, as you will also see, and the condition doesn't trigger.

All I see is undefined. It's as if my .env file doesn't even exist.

Here is my code in its current state. Any help would be appreciated.

import express from "express";
import cors from "cors";
import multer from "multer";
import AWS, { PutObjectCommandOutput, S3, S3ClientConfig } from "@aws-sdk/client-s3";
import { createReadStream } from "fs";
import path from 'path';

const dotenvAbsolutePath = path.join(__dirname, '.env')

const app = express();
const port = 5000;
// require('dotenv').config();
const dotenv = require('dotenv').config({
  path: dotenvAbsolutePath,
});
if (dotenv.error) {
  console.log(`DOTENV ERROR: ${dotenv.error.message}`);
  throw dotenv.error;
}

const keys = {
  key: process.env.AWS_ACCESS_KEY_ID,
  secret: process.env.AWS_SECRET_KEY,
  region: process.env.AWS_REGION
};
console.log(dotenv);

const upload = multer({
  storage: multer.diskStorage({ destination: "./tmp" }),
});

const s3 = new S3({
  credentials: { accessKeyId: keys.key!, secretAccessKey: keys.secret! },
  region: keys.region!
});

app.use(cors());

app.post("/", upload.single("pdf_upload"), async (req, res) => {
  let fileName: string | undefined;
  // let fileBuffer: Buffer | undefined;
  let uploadResponse: PutObjectCommandOutput | undefined;

  if (req.file) {
    fileName = req.file.originalname;
    // fileBuffer = req.file.buffer
    console.log("HTTP Request Received");
    const fileReadStream = createReadStream(req.file!.path).on(
      "ready",
      async () => {
        try {
          console.log("Stream is Readable");
          console.log(fileReadStream.bytesRead);
          uploadResponse = await s3.putObject({
            Bucket: "fiberpunch-test",
            Key: fileName,
            Body: fileReadStream,
          });
          res.header("Access-Control-Allow-Origin", "*");
          res
            .send({ file: { ETag: uploadResponse.ETag, Key: fileName } })
            .status(200);
        } catch (err: any) {
          console.log("Upload Error: ", err.message);
          res.sendStatus(500);
          console.log(fileReadStream.bytesRead);
        }
      }
    );
  }
});

try {
  app.listen(port);
  console.log(`listening at port ${port}`);
} catch (err) {
  console.log("ERROR SETTING UP SERVER");
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think you need to use process.env to access your env variables. Try logging process.env.AWS_ACCESS_KEY_ID

about 4 years ago · Juan Pablo Isaza Denunciar

0

Okay, I figured it out. First of all, I was working in typescript and forgot to compile. Second, the absolute path to the .env file was incorrect. After I did that, the environmental variable pull just fine.

I'm running into a new error, though:

Upload Error:  The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

I'll post another question if I can't figure this one out. Thanks, everyone.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in your .env file, you don't have to use them again to create a S3 object. AWS automatically recognizes these keys and uses them for S3 object creation. You only need region to create a S3 object.

const s3 = new S3({
  region: 'your region'
});

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda