npm init -y
create folder server
and file index.js
inside, with contents:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/api", (req, res) => {
res.json({ message: "Connected to Server" });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
npm i express
In package.json
(in root):
...
"scripts": {
"start": "node server/index.js"
},
...
npm start
and view http://localhost:3001/api to test our /api
endpoint
(from root): npx create-react-app client
In client/package.json
, add:
"proxy": "http://localhost:3001",
cd client
npm start
Now you can visit http://localhost:3001 to view your frontend
In client/src/App.js
, replace any existing code with:
// client/src/App.js
import React from "react";
import "./App.css";
function App() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch("/api")
.then((res) => res.json())
.then((data) => setData(data.message));
}, []);
return (
<div className="App">
<header className="App-header">
<p>{!data ? "Loading..." : data}</p>
</header>
</div>
);
}
export default App;
to test your api
endpoint front the frontend
Remove the client .git:
cd client
rm -rf .git
In server/index.js
, you can now replace the contents with:
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, "../client/build")));
// Handle GET requests to /api route
app.get("/api", (req, res) => {
res.json({ message: "Connected to Server" });
});
// All other GET requests not handled before will return our React app
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../client/build", "index.html"));
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
and now in the root package.json
:
// server/package.json
...
"scripts": {
"start": "node server/index.js",
"build": "cd client && npm install && npm run build"
},
...
and also add your version of node to package.json
(you can get version with node --version
)
"engines": {
"node": "your-node-version"
}
Add a root .gitignore
file, with, at the minimum:
node_modules
.env
.DS_STORE
Create heroku account and install heroku cli:
sudo npm i -g heroku
Then heroku login
Create a repo on github (or elsewhere), and add its URL as a remote
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/[YOUR_USERNAME]/[YOUR_REPO_NAME].git
git push -u origin main
Add Heroku Remote
Create an App on Heroku and then add it as a remote via the command line:
heroku git:remote -a insert-your-app-name-here
git commit -am "Deploy app to Heroku"
Now deploy to Heroku and your app will be live:
git push heroku main