Run React and Node on single Port


Let’s get Started

Building our backend

mkdir backend
cd backend
npm init -y
npm install express nodemon cors moment bcryptjs jsonwebtoken mongoose
const express = require('express');const bodyParser = require('body-parser');const mongoose = require('mongoose');const cors = require('cors');const corsOptions = {origin: 'http://localhost:3000'}//init appconst app = express();//add corsapp.use(cors(corsOptions));//Setup server PORTconst port = process.env.PORT || 5000;// parse requests of content-type - application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: true }));// parse requests of content-type - application/jsonapp.use(bodyParser.json());// Handle invalid OR 404 requestapp.use((_, res) => {res.status(404).json({success: false,message: "Invalid Request",});});
// Launch app to listen to specified portapp.listen(port, () => {console.log(`Voice app server is running on Port: ${port}`);});
npm install
npm start

Building Frontend

npx create-react-app frontend

Running both Frontend & Backend

npm run build
const express = require("express");const app = express();const bodyParser = require("body-parser");var cors = require("cors");const mongooseConnection = require("./helpers/mongoose-connection");const appRoutes = require("./routes");const path = require("path");app.use(bodyParser.urlencoded());app.use(bodyParser.json());app.use(cors());app.use(express.static(path.join(__dirname,".","build")))app.use(express.static("public"));app.use("/api", appRoutes);app.use((req, res)=>{res.sendFile(path.join(__dirname,".","build","index.html"))})app.use((_, res) =>{res.send({message: 'Not found!'})});mongooseConnection();app.listen(5000, (req, res)=>{console.log("Server is listening on port 5000");})



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi


Computer Science Graduate with MERN stack website development expertise.