Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN

12.6 Common backend API for MEAN and MERN (Node + Express + MongoDB)

Install Node.js LTS and pm2 as in Chapter 11 (NodeSource setup_22.x, then sudo npm install -g pm2), plus Nginx and Git. This API is the same for both MEAN and MERN – only the frontend changes.

sudo mkdir -p /opt/notes-api && sudo chown $USER:$USER /opt/notes-api
cd /opt/notes-api
npm init -y
npm install express mongoose dotenv

cat > .env <<'EOF'
PORT=5000
MONGO_URL=mongodb://127.0.0.1:27017/notesdb
EOF

cat > server.js <<'EOF'
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");

const app = express();
app.use(express.json());

mongoose.connect(process.env.MONGO_URL)
  .then(() => console.log("MongoDB connected"))
  .catch((err) => { console.error("MongoDB error:", err.message); process.exit(1); });

const Note = mongoose.model("Note",
  new mongoose.Schema({ text: { type: String, required: true } }, { timestamps: true }));

app.get("/api/health", (req, res) => res.json({ status: "ok" }));

app.get("/api/notes", async (req, res) => {
  res.json(await Note.find().sort({ createdAt: -1 }));
});

app.post("/api/notes", async (req, res) => {
  try {
    res.status(201).json(await Note.create({ text: req.body.text }));
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

app.delete("/api/notes/:id", async (req, res) => {
  await Note.findByIdAndDelete(req.params.id);
  res.status(204).end();
});

const port = process.env.PORT || 5000;
app.listen(port, "127.0.0.1", () => console.log(`API on 127.0.0.1:${port}`));
EOF

pm2 start server.js --name notes-api
pm2 save
curl -s -X POST http://127.0.0.1:5000/api/notes -H "Content-Type: application/json" -d '{"text":"First note"}'
curl -s http://127.0.0.1:5000/api/notes

(Run pm2 startup systemd once and execute the printed command so pm2 starts at boot.)

Low memory? Add swap before building frontends

npm install and production builds of React/Angular can need more than the 1 GiB RAM of a t3.micro. Add a 2 GiB swap file first: sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile (add /swapfile none swap sw 0 0 to /etc/fstab to keep it after reboot). Or build on your laptop and upload only the build folder with scp.

Ravindra Bagale's Tip

Many students run pm2 start but forget pm2 save and pm2 startup systemd, and the API disappears after a reboot. And keep 127.0.0.1 in MONGO_URL inside .env – the API and MongoDB are on the same server.

Lab

Chala, notes API pm2 ne chalu kara aani curl -s -X POST command ne "Mauli Dairy – aajche dudh sankalan" ashi note add kara. Mag curl -s http://127.0.0.1:5000/api/notes ne ti note disate ka te bagha, aani pm2 status ne API online aahe ka te check kara.