하나의 heroku 인스턴스를 사용해서 frontend와 backend를 동시에 호스팅하기 위해
셋업 가이드
set up folder structure
node_modules
, package.json
are for the backend
package.json
, node_modules
, .gitignore
set up frontend folder
ls -a
rm -rf .git
frontend package.json
root"proxy": "http://localhost:8000" // this is the server's base URL
set up concurrently
- front/back runs on one terminal
npm i concurrently
add concurrently
to script
"start": "node backend/server.js",
"server": "nodemon backend/server.js",
"client": "npm start --prefix frontend",
**"dev": "concurrently \"npm run server\" \"npm run client\"",**
//or
"start": "node backend/bin/www",
"server": "nodemon backend/bin/www",
"client": "npm start --prefix frontend",
**"dev": "concurrently \"npm run server\" \"npm run client\"",**
set up axios
in the frontend so that it just calls the api route without the url
serve static assets if in production - serve the frontend react app (build file)
backend server.js
- serve frontend
// import path
const path = require('path')
// paste code below 'Routes' logic
// Serve Frontend
if (process.env.NODE_ENV === 'production') {
// Set build folder as static
app.use(express.static(path.join(__dirname, '../frontend/build')))
// FIX: below code fixes app crashing on refresh in deployment
app.get('*', (_, res) => {
res.sendFile(path.join(__dirname, '../frontend/build/index.html'))
})
} else {
app.get('/', (req, res) => {
res.status(200).json({ message: 'Welcome to the Party-Invitation API' })
})
}
add to script
"scripts": {
"start": "node backend/server.js",
"server": "nodemon backend/server.js",
"client": "npm start --prefix frontend",
"dev": "concurrently \"npm run server\" \"npm run client\"",
**"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix frontend --legacy-peer-deps && npm run build --prefix frontend"**
},
install heroku CLI
go to terminal and
heroku login
heroku create <project name>
set environment variables in heroku
NODE_ENV = production
MONGO_URI = your mongo uri
Deploy - to see instructions, go to heroku dashboard > deploy
heroku git:remote -a <project name>
git push heroku main
run the app - heroku open
(optional) connect github
use keepawake to keep it alive