FSF-PT-08-MERN-STARTER
M - MongoDB E - Express R - React N - Node
Basic Setup
touch server.js
npm init -y
npm install express mongoose
Build the Express App
- Require express.
- Create an instance of express.
- Set the server PORT to 3001.
- Listen on the PORT
- Add middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
- Create your routes.
Add MongoDB/Mongoose to the Server
- Require mongoose in the server.js
- Setup the mongoose connection
- Add mongoose config object to the .connect method.
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
}
- Optional: include connection.on("error");
Add React to the App
npx create-react-app client
- Add a proxy to the client package.json
"proxy": "http://localhost:3001",
Configure a script to run express and react at the same time.
- cd back into the server root
npm install concurrently if-env
- Modify scripts in server package.json
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:prod": "node server.js",
"start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
Deploy App to Heroku
git add .
->git commit -m
heroku create
git push heroku main
- Add three more scripts to the server package.json
"install": "cd client && npm install",
"build": "cd client && npm run build",
"heroku-postbuild": "npm run build"
- Require path in server.js
- Statically server the
client/build
folder. - On a final, wildcard route, serve up the index.html from the
client/build
directory.
app.use(express.static("client/build"));