Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get environmental values into typescript file

I have a server.ts file

require('dotenv').config()
import app from "./app";
// Test
//const port = 4040;
app.listen(port, function() {
  console.log('Express server listening on port ' + port);
});

In my app root folder I have an .env file

PORT=4040

My package json file is basic at the minute :

{
  "name": "Node TS app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc",
    "dev": "ts-node ./lib/server.ts",
    "start": "node ./dist/server.js",
    "prod": "npm run build && npm start"

  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.11.0",
    "body-parser": "^1.18.2",
    "dotenv": "^4.0.0",
    "express": "^4.16.2"
  }
}

I want to get the PORT into the TS file. In VS Code I get an error as port can't be found. Also the npm run dev fails with similar error.

I'm compiling TS to ES5.

Any ideas how I get the value in scope?

like image 985
Leehbi Avatar asked Jun 24 '26 12:06

Leehbi


1 Answers

Dotenv library is used to load all the configuration to ENV variables in your system. You should do the following:

1 . Make sure to keep all the configuration in .env file in root directory of the project to avoid custom configurations.

2 . Load dotenv configuration before starting application.

node -r dotenv/config path/to/build/index

3 . Access configuration from env

const PORT = <number>process.env.PORT;
like image 56
Kacper Wiszczuk Avatar answered Jun 26 '26 02:06

Kacper Wiszczuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!