DEV Community

Zobaidul Kazi
Zobaidul Kazi

Posted on

How to use `.env` file v:20.6.0 `dotenv` npm package do not use.

package.json file


  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon --env-file=.env index.js",
    "start": "node --env-file=.env index.js",
    "prod": "node --env-file=.env.prod index.js",
    "local": "node --env-file=.env.local index.js",
    "build": "node --env-file=.env build.js",
    "clean": "node --env-file=.env clean.js"
  },
Enter fullscreen mode Exit fullscreen mode

Create A new Project

mkdir test_env
Enter fullscreen mode Exit fullscreen mode

cd test_env

open terminal and write this commend

npm init -y
Enter fullscreen mode Exit fullscreen mode
touch .env

Enter fullscreen mode Exit fullscreen mode

write code .env file

# write code .env file
PORT = 3333
MONGO_DB_URL = mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true
PRIVATE_KEY = <private_key>
Enter fullscreen mode Exit fullscreen mode
touch index.js
Enter fullscreen mode Exit fullscreen mode
import express from "express";
import mongoose from "mongoose";

const app = express();


app.listen(process.env.PORT | 3000, () => {
    console.log(` Listening on port ${process.env.PORT}`)
})

mongoose.connect(process.env.MONGO_DB_URL, {
    dbName: "test",
    authSource: "admin"
})

.then(() => {
    console.log("Connected to MongoDB");
})
.catch((err) => {
    console.log(err);
})

Enter fullscreen mode Exit fullscreen mode

Top comments (0)