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

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

AWS Cloud

12.4 MEAN and MERN architecture

For Mauli Dairy’s notes app, the browser presents a screen. In one client-rendered deployment, Nginx serves the built frontend and forwards requests under /api/ to Express on Node.js. The backend reads the MongoDB collection. Other rendering and hosting choices are possible.

MEAN combines MongoDB, Express, Angular and Node.js. MERN uses React for the interface. Browser and server code can both use JavaScript, but they run in different environments. MongoDB stores BSON documents, which the API can map to public JSON fields.

In the example below, the browser reads static files from Nginx and requests data through the same origin. Nginx proxies /api/ paths to Express on a private address. The backend then queries MongoDB. The server, database and process supervisor use the endpoints selected for the deployment.

Check whether the selected project outputs static browser files, a server-rendered runtime, or both. Read its actual package scripts and framework configuration. Deploy the intended build artifacts and runtime. Keep frontend routes and API errors distinguishable.

Ravindra Bagale's Tip

Use the production build and runtime for the app’s rendering mode. In this client-rendered example, Nginx serves static assets and sends API traffic to a private backend. Keep the database off the public entry point.

Lab

खाली दिलेल्या खाजगी lab मध्ये Mauli Dairy च्या दोन screens एका Express API मधून तोच note वाचतात. Browser, Nginx, Express आणि MongoDB यांचे connections वेगळे लिहा. नंतर stored note बदलून दोन्ही screens मध्ये कोणता निकाल दिसायला हवा ते तपासा.

Two screens can ask one backend for the same delivery note

The staff at Mauli Dairy want to see whether the morning delivery has arrived. At the receiving desk the record should appear in a list by delivery ID. At the counter a simpler screen should show the latest status in large text. The screens can look different and be built by different teams. Both should read the same saved delivery note. The shop will have more trouble if each screen stores its own copy and makes decisions on different data. Start by agreeing on the way a screen asks for a note and the type of response it should receive.

Here the note with ID morning-1 has a title, “Milk cartons,” and a status initially set to “received.” The service offers the HTTP route GET /api/notes/morning-1. A route is a method and path that an application knows how to handle. A shop developer can use the same route from either a React screen or an Angular screen, provided both callers understand the rules. This contract includes the path, accepted ID shape, method, response fields, field types and error meanings. It is the agreement between callers and the application. The server does not need to decide what a note card looks like, and the screen does not need to know the database address.

The practical designs in this chapter use a web server in front of the API and a document database behind it. Web browsers contact the public entry point and can receive HTML, CSS and JavaScript. HTML describes the page, CSS controls presentation, and JavaScript runs interactive behavior. The API is an application programming interface, a defined way for a program to ask another program to do a specific job. Here one API operation asks for a note by ID. The API code runs separately under Node.js, a JavaScript runtime outside the browser. This helps a beginner separate the name of a language from the environment and resources where its instructions actually run.

MEAN usually stands for MongoDB, Express, Angular and Node.js. MERN replaces Angular with React. Angular is a web application framework with features such as component composition, routing and forms. React is a user interface library built around components. A component represents some part of the screen and its behavior, such as the dairy note and a reload button. React projects commonly use a framework or choose further tooling for routing and building. The letters name a combination, not a mandatory product topology. Nginx is a useful optional entry point in this course and not the N in those acronyms.

At first this sounds like JavaScript everywhere. The API and browser interface can both use JavaScript or write TypeScript that their tooling transforms for a runtime. TypeScript lets developers describe types during development. The browser still receives runnable output. MongoDB makes its own decisions about storing and querying data. Nginx reads its own configuration format. Typing a key in a frontend component does not grant permission to run a database command. Recognizing those boundaries helps you keep secrets, business rules and database writes where they belong.

Imagine adding a third dashboard later. If it uses the stable route and response shape, it can share the existing note instead of borrowing markup from a second website or opening the database itself. If the backend later changes how it stores notes, it can preserve this HTTP behavior and update its storage code independently. The previous stack roles lesson introduced this separation with two storage implementations. This page follows it using the two work spaces the store actually needs.

Trace page delivery and later data retrieval in order

When a receiving clerk opens the board, there are two different exchanges to follow. First the browser requests the page and any assets it needs. An asset is a file used by the page, like a compiled JavaScript bundle, a style sheet or a logo. One way to deploy a client-rendered app is for Nginx to read these files and return them to the browser. The browser parses the HTML and executes the downloaded application code. A button may now show a loading message while it asks the API for separate data. The note need not have been embedded in the HTML file the web server read from disk.

Second, code in the browser sends a new HTTP request to /api/notes/morning-1. The path starts with a slash and no other hostname, so in the lab it uses the page's origin. A web origin includes a scheme, a host and a port. If a browser got the UI from http://127.0.0.1:18904, it sends that request to the same origin. Nginx routes the API prefix to a private Node listener. This time the response is generated by the backend. You can see the new request in browser network tools or reproduce the HTTP exchange from the command line.

  1. Nginx knows which kind of work this path needs. For the board document it serves the expected static file. For a path under /api/ it acts as a reverse proxy, receiving the client request and passing it to the intended private HTTP service. A reverse proxy hides where that service runs from the caller's normal URL and can help give several services one public entry point.
  2. Express identifies the action. Express is a library in the Node process that matches the HTTP route and calls the app's chosen handler function. The route definition marks one segment as a parameter. The handler verifies that the incoming ID has the allowed form before it opens a query. At this point the app can return a controlled bad-request response for the wrong shape without treating it as a database problem.
  3. Node observes MongoDB's answer. The backend uses the MongoDB Node.js driver to look up one document. A driver is code that speaks the database's protocol on the application's behalf. The database stores many documents in a collection. A collection provides the group where the app looks for a record such as morning-1. The work uses a privileged local connection in this fixture and a narrower authenticated backend identity in a deployed version.
  4. The handler maps the stored record to an HTTP result. MongoDB's document contains an internal _id key. The API can send it as id and choose which other fields are public. This means the written response can preserve old clients even when the storage representation grows extra fields. In this lesson the record still has a title and a status. Express sets the response status and sends a JSON representation with the fields consumers expect.
  5. The screen interprets the result. A browser can receive a complete HTTP response with status 404. Completion means HTTP got to a response, not that the note exists. Code checks whether the status is successful, then interprets the expected body fields and updates the display. The screen handles loading, success and error states. A frontend defect can make it display stale text even when the backend code and database correctly handle the request.

This trace also separates an HTTPS connection from a SQL or MongoDB login. An origin can serve an HTTPS site to the browser and make its own local or secured private connection to an API. The API makes a different connection to its database and controls its own rules. A visitor who knows the public API path should still face whatever authentication and authorization the application requires for that action. Hiding the database network address and keeping the frontend same-origin do not automatically decide which employee may see a note.

An API can be implemented with an ODM such as Mongoose. ODM stands for object-document mapper. It provides abstractions for modeling documents in application code and interacting with a document database. It is one option for putting schema rules and data operations in the Node application. This design chooses the official driver in the architecture exercise to make the storage handoff visible. A future lesson can use another valid library without changing which connection the browser makes or who is responsible for validating requests.

MongoDB represents documents in BSON, a binary serialization with types such as dates and object identifiers as well as familiar values such as strings and arrays. Public JSON need not expose those BSON types or all the stored fields. The example deliberately uses simple string IDs and public field names. Many applications use a database-generated ObjectId, and an API often serializes that ID to a particular text representation for its clients. Document the representation that belongs in the HTTP route. A database query matching a string is not automatically equivalent to querying a stored object identifier with the same-looking text.

Choose who renders the interface and how to ship it

A user interface can start with a mostly empty HTML shell and build its screen using JavaScript in the browser. It can also start with HTML rendered on a server for each request, or serve HTML computed before deployment. The different methods are all forms of rendering, meaning turning data and component code into content a visitor can see. With hybrid routing, some pages might be prerendered at build time and others generated on demand. Some server-rendered experiences still send JavaScript that makes existing markup interactive on the client. Which method a particular route uses is a decision in the framework and deployment configuration.

A frontend build takes source components, styles and configuration and makes deployable output. A project that targets static client rendering might ship an HTML entry plus compressed or bundled assets. A server or hybrid build can also need a running application process and a separate collection of browser assets. If a project has paths like dist/app/browser and dist/app/server, decide which artifacts are relevant from the configured builder and framework documentation. Do not blindly point a public file root at a directory containing all output. A single-page shell example is useful because its files are easy to describe, but it does not establish a universal React or Angular deployment model.

Read the build command in the project's package scripts. A command called start could launch a development server in one project and the production server in another. Development servers often rebuild on change, expose debugging behavior or have different lifecycle expectations. A production deployment needs the appropriate build or runtime selected deliberately. Do not guess the deployment mode from the development port number. The lab uses two tiny plain HTML controls to exercise the common same-origin pattern. It does not build a React or Angular interface. The React deployment lesson and Angular deployment lesson handle framework-specific outputs.

Consider a receiving board with a deep browser route such as /receiving/today. A client router can choose that screen when it is already running in the browser. If a visitor opens the route directly, the browser sends a request for that path to the server. A purely client-rendered deployment may need a narrowly configured fallback to its HTML entry for frontend routes. Keep the API paths and static asset errors separate. A missing API route that returns a successful HTML shell can break a caller that expects JSON. A missing script that returns HTML creates a confusing implementation problem even if the navigation still loads the shell. A declared fallback should answer known frontend navigation without disguising errors elsewhere.

Browser code can be inspected by clients. Any build-time setting placed into browser JavaScript is available to the people who download it. An API base path like /api/ can be public. A database credential belongs only in an appropriately provisioned backend setting. Passing it through a tool that substitutes environment variables during the frontend build still places it in browser files if the application uses it there. This is true even when a tool calls its setting an environment variable. Think about which runtime receives the value rather than its label.

Lab: verify a browser-facing contract over a real Express and MongoDB path

Use a regular-user Bash shell with Node.js and npm from a compatible supported release, MongoDB Community Server with mongod, Nginx, curl and Python 3. The MongoDB Node.js driver and Express are normal project dependencies fetched from the package registry. This exercise pins the two top-level dependencies for repeatability and retains the generated lock file within the private folder for the duration of the exercise. A lock file records the dependency resolution for this install. Review dependency tests and updates before using any lesson version in a general application.

The lab uses actual Nginx, Express and MongoDB. Its two web pages use a small shared browser script, making the common route visible without a framework build. No MongoDB client gets exposed to an external network. The database uses a fresh Unix socket under a directory restricted to your login. This local fixture skips authentication and is only for fabricated data under your own machine account. Do not replace its bind location with a shared TCP listener or place real shop data in it. The two HTTP listeners are private loopback ports 18904 and 18914. Use other free high ports through ARCH_EDGE_PORT and ARCH_API_PORT if needed, before the first step.

Step 1. Prepare project packages and a private MongoDB process

set -eu
test "$(id -u)" -ne 0
command -v node >/dev/null
command -v npm >/dev/null
command -v curl >/dev/null
command -v python3 >/dev/null
nginx_bin=${NGINX_BIN:-$(command -v nginx || true)}
mongo_bin=${MONGOD_BIN:-$(command -v mongod || true)}
test -x "$nginx_bin"
test -x "$mongo_bin"
api_port=${ARCH_API_PORT:-18914}
edge_port=${ARCH_EDGE_PORT:-18904}
test "$api_port" != "$edge_port"
umask 077
arch_lab=$(mktemp -d /tmp/rb-js-arch.XXXXXX)
printf 'Private stack lab: %s\n' "$arch_lab"
nginx_pid=
api_pid=
mongo_pid=
stop_arch_child() {
  if [ -n "$1" ]; then
    kill -TERM "$1" 2>/dev/null || true
    wait "$1" 2>/dev/null || true
  fi
}
arch_cleanup() {
  stop_arch_child "$nginx_pid"
  stop_arch_child "$api_pid"
  stop_arch_child "$mongo_pid"
  case "$arch_lab" in
    /tmp/rb-js-arch.??????) rm -rf -- "$arch_lab" ;;
  esac
}
trap arch_cleanup EXIT
mkdir -p "$arch_lab/public" "$arch_lab/data" "$arch_lab/socket" "$arch_lab/logs"
printf '%s\n' '{"name":"private-stack-architecture","private":true,"version":"1.0.0"}' \
  > "$arch_lab/package.json"
npm --prefix "$arch_lab" install --ignore-scripts --save-exact express@5.2.1 mongodb@6.21.0
mongo_socket="$arch_lab/socket/notes.sock"
ARCH_DB_URI=$(node -p '"mongodb://" + encodeURIComponent(process.argv[1]) + "/?directConnection=true"' "$mongo_socket")
export ARCH_DB_URI
start_arch_db() {
  "$mongo_bin" --dbpath "$arch_lab/data" --bind_ip "$mongo_socket" \
    --unixSocketPrefix "$arch_lab/socket" --filePermissions 0700 \
    --logpath "$arch_lab/logs/mongo.log" &
  mongo_pid=$!
  for attempt in $(seq 1 40); do
    if test -S "$mongo_socket"; then return 0; fi
    if ! kill -0 "$mongo_pid" 2>/dev/null; then break; fi
    sleep 0.25
  done
  printf 'MongoDB did not become ready. Read %s/logs/mongo.log.\n' "$arch_lab" >&2
  return 1
}
start_arch_db

The package command uses the temporary project as its prefix. It installs packages under that directory without changing the installed global toolchain. The two network packages are downloaded before starting the database. If the registry isn't reachable, fix that prerequisite rather than trying to install dependencies into a managed project. Database initialization starts when the new server opens the empty data directory. It may print separate local socket paths. Both are inside the private socket directory and this config specifies no network bind address. Use MongoDB's own log to see where it listened.

The percent-encoding in the URI makes its Unix socket path suitable for the connection string. The socket is not a secret, but it is a local resource. It is set in the backend environment rather than written to a browser file. The first readiness loop detects a socket path. The seed command in the next block sends a real query, which verifies the server is ready to execute work before you test HTTP.

Step 2. Write an independent data probe and the shared API

cat > "$arch_lab/db.cjs" <<'JS'
const { MongoClient } = require('mongodb');
const db = new MongoClient(process.env.ARCH_DB_URI, { serverSelectionTimeoutMS: 2000 });
async function run() {
  const notes = db.db('dairy_delivery').collection('notes');
  if (process.argv[2] === 'seed') {
    await notes.insertMany([
      { _id: 'morning-1', title: 'Milk cartons', status: 'received', staffMemo: 'fixture-only' },
      { _id: 'evening-2', title: 'Curd tubs', status: 'expected' }
    ]);
  } else if (process.argv[2] === 'update') {
    const change = await notes.updateOne({ _id: 'morning-1' }, { $set: { status: 'shelved' } });
    if (change.matchedCount !== 1) throw new Error('update missed the expected note');
  } else if (process.argv[2] !== 'read') {
    throw new Error('expected seed, update or read');
  }
  const row = await notes.findOne({ _id: 'morning-1' });
  if (!row) throw new Error('known note missing');
  console.log(JSON.stringify(row));
}
run().catch(error => {
  console.error(error.message);
  process.exitCode = 1;
}).finally(() => db.close());
JS
node "$arch_lab/db.cjs" seed
cat > "$arch_lab/api.cjs" <<'JS'
const express = require('express');
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.ARCH_DB_URI, { serverSelectionTimeoutMS: 1200 });
const notes = client.db('dairy_delivery').collection('notes');
const app = express();

app.get('/api/live', (req, res) => {
  res.json({ running: true });
});
app.get('/api/notes/:id', async (req, res) => {
  const { id } = req.params;
  if (id.length < 1 || id.length > 24 || /[^a-z0-9-]/.test(id)) {
    return res.status(400).json({ error: 'invalid note id' });
  }
  try {
    const row = await notes.findOne({ _id: id }, { projection: { title: 1, status: 1 } });
    if (!row) return res.status(404).json({ error: 'unknown note' });
    return res.json({ id: row._id, title: row.title, status: row.status });
  } catch (error) {
    console.error('note database read failed:', error.name);
    return res.status(503).json({ error: 'notes temporarily unavailable' });
  }
});
app.use((req, res) => {
  res.status(404).json({ error: 'unknown route' });
});

const server = app.listen(Number(process.argv[2]), '127.0.0.1', () => {
  console.log('private API ready');
});
server.once('error', error => {
  console.error(error.message);
  process.exitCode = 1;
});
process.once('SIGTERM', () => {
  server.close(() => client.close());
});
JS
node --check "$arch_lab/api.cjs"
node "$arch_lab/api.cjs" "$api_port" >"$arch_lab/logs/api.log" 2>&1 &
api_pid=$!
for attempt in $(seq 1 40); do
  if grep -Fq 'private API ready' "$arch_lab/logs/api.log"; then break; fi
  if ! kill -0 "$api_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
grep -Fq 'private API ready' "$arch_lab/logs/api.log"

The direct database helper is separate from Express and is not copied to the public folder. Use it to check what actually persisted. The initial data has one extra property, staffMemo, which this lesson uses as a private marker. Query projection chooses the database fields the API collects for the response. The public representation is also deliberately assembled with its three fields. The _id value is present by default unless a projection excludes it. Comparing the direct output and HTTP output later proves the shape boundary.

Express first checks that the path parameter is permitted. It constructs its own filter using a validated string. The handler doesn't accept a caller-supplied database filter or pass the entire HTTP request into a database operation. It distinguishes an absent note from a store that couldn't give an answer. The small liveness endpoint only establishes that the API process can respond. Liveness is evidence about the process itself. Whether a particular dependency-backed operation can complete is a separate condition worth testing.

Serve two pages and demonstrate how they share the API

Step 3. Add a shared browser script and the Nginx route

write_screen() {
  local filename=$1 title=$2
  cat > "$arch_lab/public/$filename" <<HTML
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>$title</title>
<h1>$title</h1>
<button id="load" type="button">Load morning note</button>
<p id="display" aria-live="polite">No note loaded</p>
<script src="/load-note.js" defer></script>
</html>
HTML
}
write_screen desk.html 'Receiving desk'
write_screen counter.html 'Counter board'
cat > "$arch_lab/public/load-note.js" <<'JS'
const display = document.querySelector('#display');
const load = document.querySelector('#load');
load.addEventListener('click', async () => {
  load.disabled = true;
  display.textContent = 'Loading the note…';
  try {
    const response = await fetch('/api/notes/morning-1', { cache: 'no-store' });
    if (!response.ok) throw new Error('HTTP ' + response.status);
    const note = await response.json();
    if (typeof note.title !== 'string' || typeof note.status !== 'string') {
      throw new Error('unexpected note data');
    }
    display.textContent = note.title + ' — ' + note.status;
  } catch {
    display.textContent = 'The note could not be loaded.';
  } finally {
    load.disabled = false;
  }
});
JS
node --check "$arch_lab/public/load-note.js"
cat > "$arch_lab/nginx.conf" <<NGINX
worker_processes 1;
pid "$arch_lab/nginx.pid";
error_log "$arch_lab/logs/edge-error.log" notice;
events { worker_connections 64; }
http {
    types { text/html html; application/javascript js; }
    access_log "$arch_lab/logs/access.log";
    server {
        listen 127.0.0.1:$edge_port;
        server_name localhost;
        root "$arch_lab/public";
        location /api/ {
            proxy_pass http://127.0.0.1:$api_port;
        }
        location / {
            try_files \$uri =404;
        }
    }
}
NGINX
"$nginx_bin" -t -p "$arch_lab/" -c "$arch_lab/nginx.conf"
"$nginx_bin" -p "$arch_lab/" -c "$arch_lab/nginx.conf" -g 'daemon off;' &
nginx_pid=$!
for attempt in $(seq 1 40); do
  if test -s "$arch_lab/nginx.pid"; then break; fi
  if ! kill -0 "$nginx_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
test "$(tr -d '[:space:]' < "$arch_lab/nginx.pid")" = "$nginx_pid"

The two pages would be the output of different frontend build teams in a more complex project. Here they are tiny labeled pages with an accessible live message and one normal button. Both download an identical script. When selected, the script makes a fresh request at a relative path. It interprets the same output format and puts values into the page as text. The rendering does not interpolate the database result into raw HTML. The UI disables the button while loading and turns it on when the request finishes. That makes changes in progress visible and keeps the paths easy to observe.

The key Nginx directive for this lab is proxy_pass with an HTTP upstream and no URI part after its port. This configuration passes the original request URI to the upstream for the matching API locations, rather than replacing the /api/ segment with a different path. This matches the route Express declares. A configuration that changes the prefix must agree with the Express routes. A missing slash where the team expects prefix replacement can alter both a happy path and a 404. In this exercise an unrecognized API request reaches the API's JSON error response, while a nonexistent page stays a separate static error at the web server.

Notice three different URLs that can be useful while testing. The public-shaped request goes to the front listener. A private diagnostic request can go directly to the API's loopback address from the same machine. The Mongo connection string goes to the server's private Unix socket. Using direct API checks for triage is fine in a controlled lab, but the browser in the exercise has no reason to know that high port. Checking only a private port would miss a reverse proxy that changes the path or serves the wrong public content.

Step 4. Verify the pages, status handling and direct database evidence

arch_request() {
  local route=$1 expected=$2 actual
  actual=$(curl --noproxy '*' --silent --show-error --max-time 8 \
    -D "$arch_lab/headers" -o "$arch_lab/body" -w '%{http_code}' \
    "http://127.0.0.1:$edge_port$route")
  printf '%s %s\n' "$actual" "$route"
  test "$actual" = "$expected"
}
check_note() {
  python3 - "$arch_lab/body" "$1" "$2" "$3" <<'PY'
import json
from pathlib import Path
import sys

note = json.loads(Path(sys.argv[1]).read_text())
expected = dict(id=sys.argv[2], title=sys.argv[3], status=sys.argv[4])
assert note == expected and all(isinstance(value, str) for value in note.values()), (note, expected)
print(note)
PY
}
arch_request /desk.html 200
grep -Fq 'Receiving desk' "$arch_lab/body"
arch_request /counter.html 200
grep -Fq 'Counter board' "$arch_lab/body"
arch_request /load-note.js 200
grep -Fq "fetch('/api/notes/morning-1'" "$arch_lab/body"
arch_request /api/live 200
grep -Fq '"running":true' "$arch_lab/body"
arch_request /api/notes/morning-1 200
grep -qi '^Content-Type: application/json' "$arch_lab/headers"
check_note morning-1 'Milk cartons' received
arch_request /api/notes/evening-2 200
check_note evening-2 'Curd tubs' expected
arch_request /api/notes/unknown-3 404
grep -Fq 'unknown note' "$arch_lab/body"
arch_request /api/notes/WRONG 400
grep -Fq 'invalid note id' "$arch_lab/body"
arch_request /api/other 404
grep -Fq 'unknown route' "$arch_lab/body"
arch_request /unknown.html 404
if grep -Fq 'unknown route' "$arch_lab/body"; then exit 1; fi
node "$arch_lab/db.cjs" update > "$arch_lab/direct.json"
python3 - "$arch_lab/direct.json" <<'PY'
import json
from pathlib import Path
import sys

note = json.loads(Path(sys.argv[1]).read_text())
assert note["_id"] == "morning-1" and note["status"] == "shelved"
assert note["staffMemo"] == "fixture-only"
print("Independent database read confirms the saved status and internal field.")
PY
arch_request /api/notes/morning-1 200
check_note morning-1 'Milk cartons' shelved

Each curl path is sent through the same listener a browser uses in this exercise. Verify the file markers before looking up the note. Then check API media type and parse the three fields rather than accepting “some response text.” A media type tells the client what kind of response it received. HTML and JSON can both have a 200 status. An API client that expected structured JSON may be unable to interpret an error page with the wrong format. The distinct record at the second ID also prevents a mistaken hard-coded route from passing all tests.

Updating the private document changes the status from received to shelved. The helper uses a separate client instance, and the HTTP test then proves the record reached the public contract through Nginx and Express. The storage output contains the internal note field but the API comparison requires exactly three allowed fields. The browser scripts can remain unedited through this change. If you open both pages on the machine running the lab, use their buttons before and after the update to see the same shared result. The command-line checks cover HTTP bytes and data, while that extra browser observation covers the user interface behavior itself.

Step 5. Prove dependency failure and restore the document

stop_arch_child "$mongo_pid"
mongo_pid=
arch_request /counter.html 200
grep -Fq 'Counter board' "$arch_lab/body"
arch_request /api/live 200
arch_request /api/notes/morning-1 503
grep -Fq 'notes temporarily unavailable' "$arch_lab/body"
grep -Fq 'note database read failed:' "$arch_lab/logs/api.log"
arch_request /api/notes/WRONG 400
start_arch_db
node "$arch_lab/db.cjs" read > "$arch_lab/direct.json"
grep -Fq 'shelved' "$arch_lab/direct.json"
arch_request /api/notes/morning-1 200
check_note morning-1 'Milk cartons' shelved
arch_cleanup
trap - EXIT
test ! -e "$arch_lab"
printf 'Private architecture fixture removed.\n'

Just the database child stops, so static delivery and the API's liveness route still work. The accepted note lookup returns a controlled unavailable result and records a private failure in the API log. Once the same database directory is opened again, a direct client observes the saved note and a new HTTP read matches it. The bad-ID verification distinguishes validation from unsuccessful persistence. The final cleanup stops the two listeners and the current MongoDB child and then removes the test files. Any records and package dependencies created by the one run belong to that private workspace.

Give each company network connection an intended caller

Picture the dairy moving the exercise to its own EC2 environment. Visitors are supposed to approach the HTTP entry point. The Node API is called by the entry point. MongoDB is called by the Node application. Draw a separate arrow for each connection even if some components will share a virtual machine. Write down who initiates the connection, the nearest receiving service, the actual destination port or socket and whether the connection needs TLS. This sketch makes the permitted connections auditable. It also shows why opening every installed service to the Internet is not part of preparing a frontend to work.

ConnectionTypical intentionEvidence relevant to this exercise
Browser to HTTP entry pointUse the site's intended hostname and TLS in a deployed applicationPage, script, and API path respond through the same loopback origin
Nginx to ExpressForward the path through an authorized private connectionExpress returns the correct note and generates its own JSON response for unknown API routes
Express to MongoDBConnect privately and authenticate with scoped privileges in a real deploymentThe temporary Unix socket is inside a directory limited to the learner's login
Operator to administrative toolsUse a separate authorized management path and record sensitive changesThe independent script runs under the learning account and does not live in the published file directory

If the Nginx and Node processes remain on the same EC2 server, binding the private HTTP API to loopback can meet their need to communicate. Loopback is the interface that lets programs communicate within the same operating system. A different machine's loopback is itself. When the backend moves to another private instance or container environment, its endpoint must be reachable inside that deployment. An AWS security group can restrict which application or proxy resources open a connection. Check the chosen private topology and AWS's supported reference rules. The socket path used locally does not carry over automatically to a managed, network-based database deployment.

Network policy, app permissions and database roles all matter. A security group limits connections at the network boundary. An app identity can still ask for a specific API action when it reaches the HTTP listener. The app must ensure the requesting user is allowed to perform it. A database login then needs the operations required to perform that action. If the clerk may read one group of notes but not another, a database that listens privately does not automatically express the company's business rule. The API or carefully planned database policy must enforce that distinction. Include both permitted and forbidden cases in a deployed app's verification.

A same-origin proxy design often simplifies cross-origin browser behavior. Consider a frontend from https://dairy.example and an API at https://api.dairy.example. These are different origins because the hostnames differ. The browser uses CORS, Cross-Origin Resource Sharing, to decide whether frontend code can use the response, and some kinds of scripted requests also involve a preliminary permission request called a preflight. CORS headers do not authenticate the worker or stop every possible request from reaching an endpoint. Command-line clients are not subject to that browser enforcement. Choosing the same public origin can avoid a CORS requirement for this particular UI-to-API call, while proper authorization remains necessary.

Where the delivery notes include real staff data, consider what is needed in the UI response. The direct probe shows staffMemo straight from the document. The public API omits it. You could later add a dedicated authenticated route for authorized receiving staff. A separate response representation makes that intent visible and can evolve without sending every field to everyone. Avoid building a general operation which relays arbitrary database filters and values supplied by the client. Validate the requested key, constrain the available actions, and explicitly choose which fields belong in the response. The internal-data comparison in the lab offers a repeatable starting check.

Inspect logs using the same boundary discipline. Operations may need the route, approximate processing time and response status. Logging credentials, entire documents or all query/request data makes routine troubleshooting expose more than it needs. Set a consistent correlation ID strategy if the edge and API have separate logs. A correlation ID is a value used to connect events related to one request. Use it to trace a failure without reproducing the visitor's private notes in every layer. Link one sample from Nginx, one from the API and the corresponding database error where your deployment can safely provide it.

Turn a vague report into a test that can separate the layers

The counter board opens and shows its header, but the note remains blank. Seeing text from the HTML tells you the browser reached enough of the entry point to get a page. It says nothing yet about the JavaScript bundle, the API or the data. Look in the browser's network requests. Confirm the script URL succeeds with a suitable content type and correct bytes. Then select the board button, check whether a second request appears, and compare its real path, status and body with the contract. In the lab, /api/notes/morning-1 should return three text fields. If the browser didn't request it at all, investigate browser script loading and event handling first.

Now imagine the API URL returns a successful HTML body which begins with the receiving page's title. The note route is likely hitting a frontend application's fallback or another incorrect mapping. Once the client tries to parse that as JSON, it cannot satisfy the note contract. Reproduce the exact path through the edge and, in an authorized diagnostic environment, compare the same path on the private backend. If the backend returns JSON directly, inspect URL rewriting and location matching at the front door. A targeted test for the API's unknown path helps catch any fallback rule that returns a home page indiscriminately. The goal is the right representation from the right service for both success and failure.

A second incident reports 503 and an unavailable reason in JSON, while the static page and /api/live still succeed. That combination proves pieces of both Nginx and Express are serving traffic. It directs investigation toward the dependency-driven route. Check the actual database endpoint, service readiness, permission and query evidence. The lab deliberately stops MongoDB to reproduce one possible cause. A deployed API could return the same response for a connection timeout or an authorization failure. Treat the response as a clue and inspect the server-side evidence before assuming the exact cause.

If a developer rewrites the route accidentally so any ID returns the morning note, this case won't look broken when the first button is selected. The distinct evening note test requests the same application action with a different value and demands a different result. A valid unknown ID and malformed ID provide two more boundaries. A wrong route defaults to an API 404 rather than an HTML page; an unknown note is also a 404 but has a learner-visible error indicating the application looked up a valid route. These checks make clear what it means for two screens to share a contract.

For a manual browser test, open both loopback pages on the lab machine before you run the cleanup step. Initially each page should show its own heading and “No note loaded.” Selecting the button should update that same page, with no full reload, once the API answer comes back. If you do the browser check after the direct update in the command-line probe, expect “Milk cartons — shelved.” Open the network panel while repeating the action and compare the successful request's response to the documented body. The server access log should distinguish the two page URLs and the separate API requests. Treat visible behavior as a separate assertion from curl, which never runs the supplied JavaScript.

If you're asked whether the route is a REST API, describe the actual contract first. This example identifies a note as a resource, reads it using GET, and returns a representation with a meaningful status. REST also describes an architectural style with constraints, including using a uniform interface and requests that contain the information needed to understand them. Any application can return some text in JSON. The encoding alone does not establish those constraints. A team deciding how to share a backend gets more value from specifying the supported methods, representation and behavior than from assuming all callers use the term REST the same way.

When you design a health check, write the question it answers. A shallow liveness endpoint indicates a process can still exchange HTTP. A readiness check can inspect required dependencies or the app's ability to accept real traffic. Health checks used by an orchestrator should match its decisions. Immediately replacing many app processes every time a shared database pauses may add disruption without fixing the database. An external synthetic check can exercise a known real read and measure what users need. These are different purposes. Combine them intentionally and avoid calling a simple response an end-to-end proof.

For a planned release, the team may choose to verify a note directly, then check the same note through the edge and finally have a tester load it in each interface. Changing the type or name of a public field affects frontend consumers even if the stored document is legitimate. A breaking change should go through consumer coordination and, when useful, a compatibility period. A purely visual change at the counter should keep the public data response stable. Define and test that boundary whether the browser components are JavaScript, TypeScript or something else entirely.

Check you can explain the architecture without reciting its letters

Interview questions

Where does a React or Angular screen get its data in this design?

In the client-rendered example, the browser receives the built interface and JavaScript from the site's entry point. When it needs a note, frontend code calls the documented HTTP API. The API validates the requested key, looks up a document through its backend driver and sends selected fields in JSON. Server-rendered frameworks may have a server participate before the browser requests a later update, but the database access belongs on the trusted backend.

Does using the same language across the application remove its boundaries?

Node.js and the browser can both run JavaScript. They do not share filesystem access, database access or trust. The frontend should get only its approved API settings and data. The API receives backend credentials and implements permissions. The database enforces its own roles and shapes, using a distinct protocol. Nginx routes the incoming connection before either application path runs.

How would you show that a new Angular screen can reuse an API introduced for React?

Document the actual URL, method, field types and error formats. Verify each interface calls that contract and handles known, missing and unavailable notes. Independently change a fixture record and check the interfaces read the same new value. The shared backend does not need to accept frontend-specific markup or give either UI database credentials.

Is there always a PM2 process or a live frontend port in MEAN and MERN?

The acronym does not choose a process manager or hosting method. The API may be supervised by a service manager or a container platform. A static frontend may only need its build files. Server-rendered routes may need a frontend runtime process. Identify the chosen platform, build mode, delivery server and required listeners before using particular commands.

Predict the response

The operator changes morning-1 to “shelved.” Should both screens require a rebuild?

The two test pages do not. Each makes a fresh call to the same note route when the user selects the button. The updated backend record appears through that contract without changing the public file contents. A different app may have an intentional cache or build-derived data and needs its own freshness tests.

When the only private database process stops, what continues to work?

The two static pages and the API liveness route. Those paths do not require a note query. The accepted note lookup replies with controlled unavailability. The invalid key still fails validation before a database call.

Can browser code safely carry the MongoDB password if the field uses a build environment variable?

Keep the password in a backend secret mechanism. Frontend build tools can embed configured values in assets. Once delivered, those assets can be inspected by a visitor. The frontend needs a public API location rather than the database login.

Practice tasks

  1. Sketch the two-stage path for desk.html. Mark where the HTML is read, where JavaScript runs, which request later chooses the note and where database authentication would be configured for real data.
  2. During the private run, capture one missing-note response and one unknown-route response. Compare their bodies even though both are HTTP 404. Explain what additional evidence would distinguish a server misrouting an API path to HTML.
  3. Design an independent check for the evening note after the morning update. Specify the three fields it should still return and why the morning update should have no effect on them.

One backend contract

Agree on method, path, types and errors so multiple interfaces can use one application.

Two exchanges

Page delivery sends assets. The later API exchange reads or changes data through its own route.

Private database connection

The trusted backend opens the database and sends selected result fields to the browser.

Rendering choice

Static, server-rendered and hybrid outputs require different deployments. Verify what the project actually built.

Official references