DEV Community

Agam
Agam

Posted on • Edited on

8 2

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs