Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!