DEV Community 👩‍💻👨‍💻

Agam
Agam

Posted on • Updated on

How to use express js with dotenv and ES6 modules

If you are interested in developer trends you should check out my new newsletter at: unzip.dev


I'm assuming you are using nodejs with a version later than 13.
First, you will need to change your package.json to:

{
  "name": "api",
  "version": "1.0.0",
  "type": "module", 
  ...
}
Enter fullscreen mode Exit fullscreen mode

(The type is the important part).

Now you can freely use imports, here is an express start with dotenv

import dotenv  from "dotenv"
import express from "express"

dotenv.config()

const app = express()
const port = process.env.PORT || 5000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Notes:
Having dotenv gives you the ability to add environment variables into .env files and use them easily in your express (in this case) app.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.