How to setup an Express server in a MERN environment
October 12, 2020
Initialize your project
npm init -y
This creates your package.json. Edit the description as you wish and change “main”: “server.js”
npm install the required dependencies
- express - Node.js web application framework
- bcryptjs - hashing passwords
- jsonwebtoken - JWT handling
- config - for global variables
- express-validator - request body management
- mongoose - elegant mongodb object modeling for node.js
npm i express bcryptjs jsonwebtoken config express-validator mongoose
npm install the required dev dependencies
- nodemon - node server monitor
- concurrently - Run multiple commands concurrently
npm i -D nodemon concurrently
enable ES6 modules instead of CommonJS
install the Babel dev dependencies:
npm install -D @babel/core @babel/cli @babel/node @babel/preset-env
Create a .babelrc file in the project root:
{
"presets": ["@babel/preset-env"]
}
Modify package.json, add at the top:
"type": "module",
modify “scripts” in package.json
"scripts": {
"start": "node server.js",
"server": "nodemon server.js"
},
Create basic express server
Create server.js in the project root:
import express from "express"
const app = express()
app.get("/", (_, res) => res.json({ salutation: "Hello" }))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`server started on port ${PORT}`))
Start the dev server:
npm run server
> reactContacts@1.0.0 server /home/darvat/dev/react/reactContacts
> nodemon server.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
server started on port 5000
If you now hit localhost:5000 and check devtools in chrome, you will get a proper json response:
We have successfuly created an express server that listens on port 5000 and sends you a json response when you hit the webroot.