DEV Community

loading...

How to use express js with dotenv and ES6 modules

agamm profile image Agam ・1 min read

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.

Discussion

pic
Editor guide