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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay