MERN tutorial · CodeLaunch Technologies Engineering Team · 13 October 2026

Build a small, validated REST API with Express

This walkthrough creates one endpoint for the server side of a MERN app. It demonstrates request parsing and validation before persistence; it is a learning example, not a production-ready service.

1. Create the project

Use a supported Node.js LTS release, initialize an npm project, and install Express. Add a start script such as node server.js to package.json. Commit the generated lockfile so the team installs the same dependency versions.

npm init -y
npm install express

2. Add a small, validated endpoint

Create server.js. Bound the JSON body size and validate values before using them. This in-memory example deliberately does not store data in MongoDB; the next step explains how to replace that part.

import express from "express";
import { randomUUID } from "node:crypto";

const app = express();
app.use(express.json({ limit: "10kb" }));

app.post("/api/projects", (req, res) => {
  const name =
    typeof req.body?.name === "string" ? req.body.name.trim() : "";

  if (!name || name.length > 120) {
    return res.status(400).json({ error: "A valid project name is required." });
  }

  return res.status(201).json({
    project: { id: randomUUID(), name }
  });
});

const port = Number(process.env.PORT) || 3000;
app.listen(port, () => console.log(`API listening on ${port}`));

Because the example uses ES module imports, set "type": "module" in package.json. Test it with a JSON POST to /api/projects containing a non-empty name. An invalid or missing name should receive HTTP 400; a valid request should receive HTTP 201.

3. Connect persistence thoughtfully

In a MERN application, replace the generated in-memory result with a MongoDB model and an awaited insert. Validate again at the persistence boundary, handle duplicate or unavailable database conditions explicitly, and never return database credentials or internal exception details to the client. Put connection settings in environment configuration backed by a secret manager in deployed environments.

Before exposing real user data, add authentication, record-level authorization, automated tests, and request logging that excludes secrets and private payloads. The API layer is only one part of MERN: a React client should call this endpoint and handle loading, success, and error states.

4. Keep improving the example

Add schema-based request validation, a centralized error handler, health checks, and tests for missing, malformed, and valid requests. Then make a small change and confirm the tests run in CI. Learn about our product engineering services or see our GitHub Actions CI/CD guide.