Skip to content

dotenv is not working properly as expected #145

@cinnamoroll6130

Description

@cinnamoroll6130

I'm using module-alias package with dotenv at the same time.

.env is working as expected in src/index.ts, but it's not working in other files like src/helpers/axios.ts.
I created an axios instance with api key which is loaded from .env.

I will drop the code snippets here for reference.

src/index.ts

import express, { Express, Request, Response } from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import 'module-alias/register' // Register module aliases

import { router } from './routes'

console.log(process.env.API_KEY)        // -------------------------------------> this is working properly

dotenv.config({ path: `${__dirname}/../.env` })

src/helpers/axios.ts

import axios from 'axios'

export const BASE_URL = 'https://test-base-url.com'

console.log('ENV - ', process.env.API_KEY)        // -------------------------------------> this is not working

export const swapkitInstance = axios.create({
  baseURL: EASYBIT_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'API-KEY': process.env.API_KEY,
  },
})

package.json

{
  "name": "backend",
  "version": "1.0.0",
  "main": "dist/index.js",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "concurrently -k -i -p \"[{name}]\" -n \"Node,TypeScript\" -c \"yellow.bold,cyan.bold\" \"yarn watch-js\" \"yarn watch-ts\"",
    "build-ts": "tsc --skipLibCheck",
    "watch-ts": "tsc -w --skipLibCheck",
    "watch-js": "nodemon dist/app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "axios": "^1.7.7",
    "body-parser": "^1.20.2",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "module-alias": "^2.2.3",
    "yup": "^1.4.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "^4.17.21",
    "@types/node": "^22.5.4",
    "concurrently": "^9.0.1",
    "nodemon": "^3.1.4",
    "ts-node": "^10.9.2",
    "typescript": "^5.5.4"
  },
  "_moduleAliases": {
    "@": "dist"
  }
}

nodemon.json

{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "ts-node -r module-alias/register src/index.ts"
}

Any help would be appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions