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

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

AWS Cloud

12.7 MERN: React frontend served by Nginx

Let’s build a client-rendered React notes board with Vite. Nginx will serve its browser artifacts and route note requests to the same private Express API. Other React rendering modes can require other deployment steps.

Build the React app (Vite)

Use the isolated Vite build below with the shared Notes API. Inspect the actual built HTML and asset filenames before serving them. Keep source files and credentials outside the public document root.

Nginx configuration for MERN

The example serves a separate site on a private loopback listener. Its known board URLs load the React entry. Assets use file-or-404 rules and /api/ reaches the local Node process. Compare the resulting HTTP data with a direct read of the Notes API before deciding the deployment works.

Ravindra Bagale's Tip

A static client build can run on a suitable workstation or CI runner. Deploy the reviewed build files for that mode and check the paths they reference. A server-rendered project may need its own runtime as well.

Lab

खालील खाजगी lab मध्ये React app build करा आणि local Nginx वर board उघडा. Note add करून तोच URL reload करा. मग API list मध्ये saved note दिसतो का ते तपासा.

In this Vite example, Nginx serves the browser files and proxies API requests to the shared backend. React projects can use static, server-rendered or mixed output. The next lesson checks Angular’s selected output too.

Build the counter board once and fetch fresh notes when it opens

The Mauli Dairy counter has a page for recent notes. When the receiving clerk adds “Delivery counted,” the team wants that note to appear on the counter board after someone loads it again. They do not want to ask the developer to rebuild the board every time the day's notes change. The files describing the interface and the records it displays travel by different paths. React draws the interface. The Node API receives operations on the notes. MongoDB stores the resulting documents. Nginx can provide a single entry point for both the browser-facing files and calls to the backend.

In this lesson we choose a client-rendered React app and use Vite to build its browser files. Vite is a build tool that turns a project's source into deployable output. Client rendering means JavaScript executes in the browser and produces the actual interactive interface. React manages the tree of components, such as the notes list and the add form. This project has no React server runtime because of the mode we chose. Other React projects might use a framework that also produces server-rendered or prerendered routes. Verify the actual project's configured output rather than assuming the word React implies a specific hosting model.

Keep this question in mind when choosing a build fixture: what action should end in data that survives a browser refresh? A note that appears only in one component's local memory can vanish when the page reloads. Our screen adds a note to its state only after the API confirms creation. A following request for the current list still needs to fetch the saved note. Checking the resulting data through a direct API request and the front door helps avoid confusing a visible text update with database evidence. The earlier Notes API lesson independently verifies real entries in MongoDB.

The course is practicing a specific release shape. The frontend listens through a private Nginx instance for local learning. The shared backend listens privately on a different loopback port. The frontend uses a relative API path, which makes it ask the same public-shaped server that gave it the page. A loopback training deployment does not grant authorization for a public write service. Reuse it only with your own fabricated records. Follow your application's access, TLS and hosting policy before running a shared deployment.

Separate files you edit from files the browser downloads

Begin with index.html in the Vite project. This document specifies a place in the page for React to mount and a JavaScript module to load. A module is a source unit that can import or export behavior. During development the HTML can refer to a source module such as /src/main.jsx. JSX is JavaScript syntax for writing component element trees using a markup-like structure. Build tooling converts it into runnable JavaScript for the target browser. Serving the source folders by themselves would leave parts of that workflow unfinished.

The React entry point calls createRoot on the chosen browser element and renders the main component there. You won't see the note items embedded in the source HTML. Once the browser executes the built JavaScript, the component can fetch data and produce DOM nodes. DOM stands for Document Object Model and is the browser's representation of the page that scripts can manipulate. React updates that representation when the state changes. State is data a component retains for later render passes, such as which note entries are available, the current draft and whether a request is pending.

The selected Vite build writes a new public dist directory. It has an HTML entry and built assets under an assets path. It updates the HTML so it refers to the generated asset URLs. An asset is a file the browser uses, such as a JavaScript bundle or style rules. In this build the generated filenames contain a content-derived identifier. That makes it possible to cache the immutable asset more aggressively, provided you publish new bytes under new names and retain the old files long enough for older pages still in circulation. The project recipe should prove that the browser-facing URL matches the path emitted in dist/index.html.

The page URL and the built asset URL do not have to be the same folder on the source machine. In our deployment the app is at the origin's root. If a real site needs /notes-board/ instead, review Vite's public base path and the web server mapping together. An absolute built asset path pointing at the public root may be wrong for a bundled site under another prefix. Separately decide how the frontend finds its API. The lab uses /api/notes on the origin. Moving the application pages beneath a prefix need not move that public API route. Keep tests for each URL instead of relying on a file tree that happens to look right.

File or decisionWhere it is usedEvidence
React JSX and imported client helperSource consumed during frontend development and buildThe project can build a compatible browser bundle
Built HTML and assetsNginx public document rootHTML, exact hashed bundle, correct media type and cache policy all return as intended
API route and credentialClient knows the public path, backend owns private settingsJSON comes through the same-origin path and secrets remain outside browser assets
MongoDB noteDatabase behind the shared APIRefresh and independent API lookup find the stored text and the same ID

Copying the wrong directory can create a misleading success. Imagine placing a new project's root under Nginx and seeing a default page while its JavaScript fails. The status on the HTML alone can't prove React ran. Inspect the built HTML and confirm the exact script path it refers to. Open that URL and verify the response is actually JavaScript. Then use the browser's network view to confirm the application requested the note API. The difference between a successful build and a successful deployment is a path the client can actually follow.

Give frontend navigation, assets and the backend different routing rules

The board has two known page URLs: its main entry and /board/recent. Opening the second directly means the browser asks the web server for that path before React has loaded. This exercise configures Nginx to return the same entry HTML document for those two intentional routes. When the script starts, its path check can choose a recent-board heading. This is a narrow demonstration of a client-rendered deep link. A larger project may use a router library, route parameters or a framework convention. The configured server must still return the intended page entry or error for the specific URL.

A request for an asset or API must never accidentally take the same fallback branch. If /assets/old-name.js no longer exists and Nginx returns app HTML with a 200 status, the browser may reject the script due to the wrong media type. If /api/missing receives the HTML entry, the frontend cannot handle the JSON error it expected. A fallback that applies broadly can hide deployment faults because the raw HTTP status looks successful. Give static assets an explicit file-or-404 rule. Forward the API route to Express and allow it to return application JSON errors. Refuse unknown navigation in this small project instead of using a broad catch-all.

Nginx can replace a matched location prefix with the URI part of a proxy_pass target. For example, the given API already expects /api/notes. The experiment uses proxy_pass with the upstream address and no replacement URI, so the original API path reaches Express. A configuration with a trailing slash can mean a replacement URI in that context. This is why apparently equivalent proxy statements sometimes produce different application 404 responses. Compare the same path directly with the backend and through Nginx when debugging. Use the documentation for the version and exact location form rather than assuming every trailing slash rule works the same way.

Caching is another routing concern. If the visitor receives an old HTML entry, it can refer to an old bundle name. A staged new version should have its referenced files ready before the entry switches. Revalidating HTML and retaining old hashed assets help avoid mixed releases. Hashed assets can have a longer cache lifetime if they are never overwritten with different bytes. Dynamic notes have separate freshness requirements. Serving them through a same-origin endpoint does not mean they should share a year-long browser cache with JavaScript files. This training code chooses no-store for its reads to make fresh data observable during the exercise.

Lab: build and serve one working React production bundle

First perform Steps 1 and 2 of the shared Notes API lab in Bash. Stop after it starts the API and sets notes_url. Keep the same shell and start with a fresh fixture rather than a database holding previous exercise notes. That gives you a real private Express, Mongoose and MongoDB path while keeping this lesson focused on the frontend. Use an ordinary account. The same-session requirement lets both lessons keep their cleanup tied to the exact children they started.

You also need an installed Nginx executable and the Node and npm tools used by the API. The example uses exact React and Vite versions for a reproducible exercise. Check the Vite and React project documentation when applying this to a different project. Choose an available local port, 18905 by default using REACT_EDGE_PORT to override. Use NGINX_BIN if your executable is not in the shell path. The edge port must differ from the earlier API port. All browser interactions in this lesson must take place on the machine with the loopback listener.

Step 1. Write the frontend source and its browser client

nginx_bin=${NGINX_BIN:-$(command -v nginx || true)}
test -x "$nginx_bin"
curl --noproxy '*' --silent --show-error --fail "$notes_url/api/ready"
react_port=${REACT_EDGE_PORT:-18905}
test "$react_port" != "$notes_api_port"
react_root="$notes_lab/react"
nginx_pid=
react_cleanup() {
  stop_notes_child "$nginx_pid"
  notes_cleanup
}
trap react_cleanup EXIT
mkdir -p "$react_root/src" "$react_root/logs"
cat > "$react_root/package.json" <<'JSON'
{
  "name": "private-dairy-react-board",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": { "build": "vite build" },
  "dependencies": { "react": "19.3.1", "react-dom": "19.3.1" },
  "devDependencies": { "vite": "8.3.8" }
}
JSON
cat > "$react_root/index.html" <<'HTML'
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mauli Dairy React board</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
HTML
cat > "$react_root/src/notes-client.js" <<'JS'
function isNote(value) {
  return value !== null && typeof value === 'object' &&
    typeof value._id === 'string' && typeof value.text === 'string';
}

export async function readNotes(send = fetch, signal) {
  const response = await send('/api/notes', { cache: 'no-store', signal });
  if (!response.ok) throw new Error('Fetch failed: HTTP ' + response.status);
  const data = await response.json();
  if (!Array.isArray(data) || !data.every(isNote)) throw new Error('Unexpected note list');
  return data;
}

export async function createNote(text, send = fetch) {
  const response = await send('/api/notes', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text }),
  });
  if (response.status !== 201) throw new Error('Create failed: HTTP ' + response.status);
  const data = await response.json();
  if (!isNote(data)) throw new Error('Unexpected created note');
  return data;
}
JS
cat > "$react_root/src/main.jsx" <<'JSX'
import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { createNote, readNotes } from './notes-client.js';
import './style.css';

function Board() {
  const [notes, setNotes] = useState([]);
  const [draft, setDraft] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('Loading notes…');
  const recent = window.location.pathname === '/board/recent';

  useEffect(() => {
    const controller = new AbortController();
    async function load() {
      try {
        const records = await readNotes(fetch, controller.signal);
        if (controller.signal.aborted) return;
        setNotes(records);
        setMessage(records.length ? 'Notes loaded.' : 'No notes yet.');
      } catch {
        if (!controller.signal.aborted) setMessage('Notes could not be loaded. Try reloading.');
      } finally {
        if (!controller.signal.aborted) setLoading(false);
      }
    }
    void load();
    return () => controller.abort();
  }, []);

  async function submit(event) {
    event.preventDefault();
    const text = draft.trim();
    if (!text || loading || saving) return;
    setSaving(true);
    setMessage('Saving note…');
    try {
      const note = await createNote(text);
      setNotes(current => [note, ...current].slice(0, 20));
      setDraft('');
      setMessage('Note added.');
    } catch {
      setMessage('The note could not be confirmed. Check the board before trying again.');
    } finally {
      setSaving(false);
    }
  }

  return (
    <main>
      <nav aria-label="Board pages"><a href="/">Board home</a> <a href="/board/recent">Recent board</a></nav>
      <h1>{recent ? 'Recent delivery notes' : 'Mauli Dairy React board'}</h1>
      <form onSubmit={submit}>
        <label htmlFor="note-draft">Delivery note</label>
        <input id="note-draft" value={draft} maxLength={200} disabled={saving}
          onChange={event => setDraft(event.target.value)} />
        <button type="submit" disabled={loading || saving || !draft.trim()}>Add note</button>
      </form>
      <p role="status">{message}</p>
      <ul aria-label="Delivery notes">{notes.map(note => <li key={note._id}>{note.text}</li>)}</ul>
    </main>
  );
}

createRoot(document.getElementById('root')).render(<Board />);
JSX
cat > "$react_root/src/style.css" <<'CSS'
:root { color: #172941; background: #faf7f0; font: 1rem/1.55 system-ui, sans-serif; }
body { margin: 0; }
main { max-width: 40rem; margin: 0 auto; padding: 1.5rem; }
nav { display: flex; flex-wrap: wrap; gap: 1rem; }
form { display: grid; gap: .55rem; max-width: 25rem; }
input, button { font: inherit; padding: .55rem; }
button { width: fit-content; }
li { overflow-wrap: anywhere; }
CSS
npm --prefix "$react_root" install --ignore-scripts
npm --prefix "$react_root" run build
test -f "$react_root/dist/index.html"
test -d "$react_root/dist/assets"

The package file lists the runtime library and the build tool separately. The runtime React code is bundled in a browser asset alongside the application. Vite does the transformation during the build. The final Nginx worker does not invoke Vite or use the node_modules folder to serve the page. Check that the build created an HTML entry and an assets directory. An error during install or build means you should resolve the dependency and Node-version requirement before changing your HTTP configuration.

The browser helper is a small representation contract check. It expects 201 for create and an array of note objects for read. A response with unexpected keys or types should not make the interface claim the operation succeeded. The React component mounts, begins one initial fetch and aborts it if the component unmounts. Aborting is a way to stop waiting for a no-longer-relevant browser request. The component checks that state before updating the screen. React can run an extra setup and cleanup cycle for Effects in appropriate development Strict Mode settings, so avoid assuming a development render prints exactly one fetch. This lab uses the built release and expects the browser to show a useful result.

An HTML form normally submits with a navigation and can reload the page. The event handler prevents that default action and asks the API to create the note through fetch. The form button remains unavailable while it is waiting. It also stays disabled until the draft has some content. Once the API returns a created object, the code prepends it using a state update derived from the prior list. That avoids the screen losing locally displayed state during its render. If creation cannot be confirmed, the user keeps the draft and gets an instruction to look before retrying. It is possible that the server saved a note before an interrupted client connection lost the response. A correct client recovery path must account for that ambiguity.

Serve only built files and wire a distinct API path

Step 2. Write a private Nginx server block

cat > "$react_root/nginx.conf" <<NGINX
worker_processes 1;
pid "$react_root/nginx.pid";
error_log "$react_root/logs/error.log" notice;
events { worker_connections 64; }
http {
    types { text/html html; application/javascript js; text/css css; }
    access_log "$react_root/logs/access.log";
    server {
        listen 127.0.0.1:$react_port;
        server_name localhost;
        root "$react_root/dist";

        location = / {
            try_files /index.html =404;
            add_header Cache-Control "no-cache";
        }
        location = /board/recent {
            try_files /index.html =404;
            add_header Cache-Control "no-cache";
        }
        location = /index.html {
            try_files \$uri =404;
            add_header Cache-Control "no-cache";
        }
        location ^~ /assets/ {
            try_files \$uri =404;
            add_header Cache-Control "public, max-age=31536000, immutable";
        }
        location ^~ /api/ {
            proxy_pass http://127.0.0.1:$notes_api_port;
        }
        location / {
            return 404;
        }
    }
}
NGINX
"$nginx_bin" -t -p "$react_root/" -c "$react_root/nginx.conf"
"$nginx_bin" -p "$react_root/" -c "$react_root/nginx.conf" -g 'daemon off;' &
nginx_pid=$!
for attempt in $(seq 1 40); do
  if test -s "$react_root/nginx.pid"; then break; fi
  if ! kill -0 "$nginx_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
test "$(tr -d '[:space:]' < "$react_root/nginx.pid")" = "$nginx_pid"
react_url="http://127.0.0.1:$react_port"
printf 'Local board: %s/board/recent\n' "$react_url"

Use the frontend build directory as the root, not the repository root. That permits only the expected release files to be mapped to URLs. The asset locations check actual file presence. Holding one last-known-good build nearby is useful, but put it outside the publicly mapped tree unless you intentionally expose some versioned artifacts. The API host in the upstream directive uses a private loopback listener created by the prerequisite. The browser does not need a direct address for it. The shell keeps the Nginx variables escaped in the here-document so the final config contains variables for Nginx, rather than trying to expand them before writing the file.

There are three representations here. The entry is HTML. Build artifacts receive their suitable media type, such as JavaScript or CSS. The API creates an application JSON response or a deliberate empty response for some operations. The fallback for the two frontend navigation paths returns the same entry HTML and allows the router-like path decision to happen in the browser after the bundle loads. It does not apply to /api/other, a bundle name, or an unknown navigational path. The separate media types and negative checks tell you which branch served each request.

Step 3. Compare the served files with the built files

react_request() {
  local method=$1 endpoint=$2 expected=$3 actual
  shift 3
  actual=$(curl --noproxy '*' --silent --show-error --max-time 8 \
    --request "$method" -D "$react_root/headers" -o "$react_root/body" \
    -w '%{http_code}' "$@" "$react_url$endpoint")
  printf '%s %s %s\n' "$actual" "$method" "$endpoint"
  test "$actual" = "$expected"
}
asset_url=$(python3 - "$react_root/dist/index.html" <<'PY'
from html.parser import HTMLParser
from pathlib import Path
import re, sys

class Modules(HTMLParser):
    def __init__(self):
        super().__init__()
        self.modules = []
    def handle_starttag(self, tag, attrs):
        fields = dict(attrs)
        if tag == "script" and fields.get("type") == "module":
            self.modules.append(fields["src"])

parser = Modules()
parser.feed(Path(sys.argv[1]).read_text())
assert len(parser.modules) == 1
asset = parser.modules[0]
assert re.fullmatch(r"/assets/[a-zA-Z0-9_.-]+\.js", asset), asset
print(asset)
PY
)
react_request GET / 200
cmp "$react_root/body" "$react_root/dist/index.html"
grep -qi '^Cache-Control: no-cache' "$react_root/headers"
react_request GET /board/recent 200
cmp "$react_root/body" "$react_root/dist/index.html"
react_request GET "$asset_url" 200
cmp "$react_root/body" "$react_root/dist$asset_url"
grep -qi '^Content-Type: application/javascript' "$react_root/headers"
grep -qi '^Cache-Control: .*immutable' "$react_root/headers"
react_request GET /assets/missing.js 404
if grep -qi '^Cache-Control: .*immutable' "$react_root/headers"; then exit 1; fi
react_request GET /unknown-page 404
react_request GET /src/main.jsx 404
react_request GET /package.json 404
react_request GET /api/invalid-route 404
grep -qi '^Content-Type: application/json' "$react_root/headers"
grep -Fq 'unknown route' "$react_root/body"

This verifies bytes and response headers before an interactive check. The extracted asset URL comes from the file you actually built. The precise filename may change with the tools and the source. Check it rather than substituting a filename from a screenshot. The fixture expects a conventional Vite-generated asset under the selected browser base. Compare the downloaded artifact with the exact output from disk, including the bytes. The missing asset route tests the failure branch and ensures there is no immutable caching directive issued for that missing file response by this config.

Opening both wired page paths gives the same entry file by design. A browser will render a different heading after reading its path. Testing the file with curl cannot execute React or run the handler. The asset tests also prove the edge won't serve files from the source tree or project root. The unknown API path must reach the backend and receive its own error. If it gets a 200 entry document, check the routing configuration before rewriting the React component. These mistakes look like frontend parsing failures even though the problem is the HTTP entry point.

Check creation and reload across the real browser path

Step 4. Run the same data client through Nginx

cat > "$react_root/verify-client.mjs" <<'JS'
import assert from 'node:assert/strict';
import { createNote, readNotes } from './src/notes-client.js';

const [edge, api] = process.argv.slice(2);
const through = origin => (path, opts) => fetch(new URL(path, origin), opts);
const viaEdge = through(edge);
const viaApi = through(api);
assert.deepEqual(await readNotes(viaEdge), []);
const added = await createNote('Counter delivery confirmed', viaEdge);
assert.equal(added.text, 'Counter delivery confirmed');
assert.match(added._id, /^[0-9a-f]{24}$/);
assert.deepEqual(await readNotes(viaEdge), [added]);
assert.deepEqual(await readNotes(viaApi), [added]);
await assert.rejects(() => createNote('  ', viaEdge), /HTTP 400/);
assert.deepEqual(await readNotes(viaEdge), [added]);
const selected = await viaApi('/api/notes/' + added._id);
assert.equal(selected.status, 200);
assert.deepEqual(await selected.json(), added);
console.log('Browser client functions and independent API agree:', added._id);
JS
node "$react_root/verify-client.mjs" "$react_url" "$notes_url"

The same client functions used by React make requests to the local edge in this check. For the command-line invocation, a small adapter resolves their relative path from the chosen origin. A regular browser already knows the page origin. After creating the note, the helper reads from the edge and directly from the backend and checks the generated ID and exact text. Rejected blank input reaches the API only in this probe, since the browser form refuses to submit a blank draft. Two layers can validate the same business rule because non-browser callers can still send requests to the backend.

For an interactive test, open the printed board URL in a browser on the lab machine before cleanup. Wait for the existing “Counter delivery confirmed” entry from the probe. Choose the field labeled Delivery note, enter “Lunch count checked,” and use Add note. Watch for the confirmation and the new item in the list. Reload the same deep URL. The recent heading and both notes should return. In network tools the app loads the HTML, generated bundle and a separate request for the list. The form sends another API request with method POST. Compare the actual status and returned ID in that response rather than assuming the visible list proves the request format.

Use this moment to check accessible states. The text field has a visible label, the submit control becomes unavailable while waiting, and the status region renders loading and completion text. A keyboard user should be able to reach the field, enter a note, focus the button and activate it. Application errors should be made visible as messages without dumping internal logs into the page. A direct page reload should make a fresh list request and show the persisted data rather than rebuilding the frontend.

Step 5. Separate a stopped database from a failed frontend build

stop_notes_child "$db_pid"
db_pid=
react_request GET /board/recent 200
cmp "$react_root/body" "$react_root/dist/index.html"
react_request GET "$asset_url" 200
cmp "$react_root/body" "$react_root/dist$asset_url"
react_request GET /api/health 200
react_request GET /api/notes 503
grep -Fq 'notes temporarily unavailable' "$react_root/body"
start_notes_db
for attempt in $(seq 1 20); do
  if react_request GET /api/ready 200; then break; fi
  sleep 0.25
done
grep -Fq '"storageResponding":true' "$react_root/body"
react_request GET /api/notes 200
grep -Fq 'Counter delivery confirmed' "$react_root/body"

The browser page and exact compiled script remain available during the storage failure. The backend's shallow health still answers. The dynamic loopback path returns the backend's 503 JSON. A reload during that interval should show the app's load-failure message. Restarting the same database process with its stored data intact restores the list. This demonstrates why an Nginx asset fix would be the wrong next step for a health combination that shows only the stored notes are unavailable.

Step 6. Stop the private processes and remove this run

react_cleanup
trap - EXIT
test ! -e "$notes_lab"
printf 'Private React board and API removed.\n'

The cleanup stops the added Nginx child before calling the original API and database cleanup. It removes the project, its installed dependencies, the build and the fabricated MongoDB data from the disposable fixture. If you placed a real lab on a cloud machine, separately remove the machine and disks you created after capturing the exercise. Do not point these commands to a normal running service or an existing website.

Distinguish client state, server state and the deployed version

Below is one release story you can use to organize a verification session. At 10:00 the clerk opens the board and sees an empty list. At 10:05 someone successfully creates “Counter delivery confirmed” and the request returns a new ID. At 10:10 the counter opens the same path in a separate tab. At 10:15 a developer changes the label of the button and stages another frontend version. Use these timestamps as labels for tests, not as constraints in the app. Each event should change a different kind of state.

EventWhat should changeWhat could reveal a mistake
First empty readThe component goes from loading to a confirmed empty listA server error or unexpected response body must have a different visible result
Confirmed createThe database stores a generated ID with the note, and the current component displays itCheck 201 and the typed object before accepting the update on the screen
Independent tabThe new component starts with different local state but requests the same stored dataA fresh list result should include the same generated ID
New button textThe source and generated frontend assets changeThe app should still consume the existing list and create contract without changing stored records

React state is usually tied to the component instance and UI lifetime. An unmounted component goes away. After a page reload, the browser runs the built code anew and opens with that initial state. The new state becomes current after it fetches from the backend. If the two tabs diverge for a moment, check whether both made fresh requests at the relevant times. This little app doesn't synchronize browser tabs continuously. It loads on entry and updates the current list after a successful create. A real live board could implement explicit refresh, periodic polling or a server-driven update if users need near-real-time changes.

The database's persisted state has a longer lifetime than one tab or one web process. Use the exact note ID to check it after refreshing. The deployed frontend version, meanwhile, can remain identical through any number of routine note edits. An edit to the React interface needs a new build and an intentional release. Database updates do not by themselves alter the frontend artifact. Ask which of these lifetimes a test actually covers before announcing that a release is ready.

There is one more useful case. Suppose the response to POST gets lost after Express committed the write. The component's failure message tells the user that it couldn't confirm the add, and it leaves the typed draft intact. Reload the board to look for the same note before retrying. In the exercise, two separate accepted POSTs can create separate records even if the text matches. A production service that promises deduplication needs a stable request identity and its own transaction behavior. The UI may show progress honestly without pretending it can tell whether a missing response means a write failed.

Keep the browser and HTTP checks separate in a release report. Curl can show the returned entry, exact bundle and structured response. The shared Node probe executes the same parsing and request functions the React component uses. A browser test then verifies mounting, labels, interaction and visible state. Each is useful. None is an automatic substitute for all the others, and a missing verification step should be named so another reviewer can run it.

Publish a coherent release instead of copying only what looks new

Imagine you improve the counter board's button, build a second release and copy its new HTML over the first version. The new HTML names a different JavaScript file. If the file has not yet arrived in the document root, some visitors receive a valid HTML page but can't start the application. The API itself can still return notes, so restarting Node does not repair the front page. Write down a release invariant: every HTML entry visible to users must refer to assets the server can deliver at the correct paths. Make that true both when rolling forward and when you need to revert.

In this fixture the server reads the selected build directly from its own private directory. A maintained deployment can publish versioned build directories. One way to prepare it is to build in CI, review the produced assets in a private candidate location, make them available under their intended URLs and then switch the HTML entry as one controlled change. CI is continuous integration, the practice of running build and verification steps automatically on candidate application changes. Keep the previous release available for a planned rollback. If an asset reference can come from an older HTML response in a browser or edge cache, preserve the needed old hashed asset while it may still be requested.

Consider two concrete cache observations. If the browser requests an old hashed file and the server still has it, serving the original bytes is consistent with the immutable policy. If the server delivers different code at that same URL, older clients may keep the old bytes for a long time and new clients may get new bytes under the identical name. This can create an inconsistent release. Produce a new filename when changing its contents. For the HTML entry, the example's no-cache header allows a cache to store a copy while requiring revalidation before reuse. That differs from no-store, the Fetch cache mode this client uses to avoid using or updating its HTTP cache for the list request. Check the actual cache policy that applies to the response at each layer.

Suppose a customer opens the board while Release A is live, then leaves the tab open during the upgrade to Release B. Their browser could keep running Release A's JavaScript after the public entry starts serving Release B. If a route later loads its own split asset lazily, the browser may ask for an old asset name. Removing every old file at the moment of release can break that visit. Consider active sessions, any asset TTL and edge behavior when choosing how long to retain artifacts. For the static exercise there is a single generated JavaScript module and a small style file. The general lesson is about references, not a guarantee every build produces the same number of files.

Rollback should verify more than the reinstated HTML checksum. Check a known JS and CSS path from that HTML, the routed direct navigation and an ordinary notes list. If an old bundle reads _id and a new API response removed that field, restoring the old frontend alone would still break it. Coordinate contract changes so two releases can overlap when appropriate. Try old and new clients with the expected response fields during staging. When an app needs a breaking contract change, either sequence work carefully or maintain a compatibility period. This is separate from staging or reversing data migrations in a backend store.

The browser artifact can be built on a suitable CI runner or development machine and then deployed. This often saves CPU and memory load on an EC2 instance that only needs to serve files. Check that the build environment matches the project's supported Node release, dependency lock and target browsers. The production web server still needs correct file access and path mapping. A project with frontend server rendering has a runtime that must also be packaged and started. Decide which deployment target you built, rather than applying a “only copy dist” rule to every framework configuration.

Build once for an identified release and store the dependency lock alongside source according to your team's approach. The exercise pins top-level dependencies and proves a build in the current fixture. Recording the returned lock lets a team repeat the package resolution. In a maintained project use a supported package update and lockfile workflow instead of relying on historical package versions indefinitely. A build's result should be independently verifiable by the artifact you served. Configuration present only on a laptop may make a test succeed there but fail in CI or across another deployment environment.

Diagnose a blank page without guessing whether React crashed

Suppose the direct deep link displays a blank screen. Start with the exact URL and network result. If the page path itself returned 404, check the edge's navigation mapping. If the HTML arrived, read the module path it declares, then check that response status, type and body. A wrong MIME type can cause the browser to reject what looks like JavaScript delivery in an access log. If the module loaded but the component failed to mount, inspect the browser console and confirm the expected root element exists. The first observation should tell you where to look before you change the application logic.

Imagine the board page and React bundle both appear correct but it shows “Notes could not be loaded.” Observe whether the browser tried the expected API path. A missing request can indicate a script did not finish initialization. A 404 with an application JSON error means an API accepted an unexpected pathname. A 404 with an edge's ordinary HTML error could mean the API branch never received it. A 200 with HTML that matches the page entry often signals the wrong navigation fallback. A 503 with the app's unavailable body means Express replied but a dependency-backed operation failed. Separate these cases even if the same UI message alerts the user to several of them.

ObservationEvidence to compare firstPotential boundary
Deep page URL 404URL, expected navigation route, actual served rootNginx site and location configuration
Page succeeds, JavaScript URL stale or wrong typeHTML asset reference, deployed files, response type and bytesBuild publication, caching or static mapping
UI rendered but new note not confirmedBrowser POST content type and body, exact status, API errorClient contract, proxy mapping or validation
Process healthy, API list unavailableSeparate readiness and direct authenticated dependency checksStorage connection or data permission
Confirmed note disappears after reloadReturned ID, reload's actual origin and GET response, independent backend readWrong store or environment, stale cache, or frontend state logic

Look closely at the last symptom. A developer might load the app from a staging origin while initially posting a note to a local origin. Both endpoints accept a valid request, but one queries a different database. Compare the browser's full effective URL and the service environment. A highly realistic test uses the same entry point as the people who report the problem. When comparing an independent direct API read, make sure you're using the same backend environment and ID. Cleanly separate already saved data from text currently in the React state. The original frontend exercise cannot prove both if it only shows the page after a form submission.

A colleague may try to point the frontend directly at http://127.0.0.1:18915 because that port worked in a shell on the server. In a visitor's browser that address means the visitor's own machine. Even a reachable second host may be a different web origin and require a deliberate CORS policy for browser access. Same-origin routing in the release lets the UI use a relative API path while Nginx alone needs to find the backend. It does not authenticate clients automatically. A secure deployed notes API still needs server-side permissions and an appropriate network boundary.

If a build accidentally includes a database secret, removing it from source is only the first repair. Any affected generated bundles may already have been served. Follow the responsible team's credential-rotation and incident procedures and remove the exposed value from the published assets. Vite's client-exposed configuration system is for values the browser is allowed to know. A predictable path for the API is appropriate. Backend secrets stay behind the HTTP response boundary. A generated script that visibly includes a connection string with credentials needs action regardless of how the original variable was named.

Review with concrete checks you could repeat for another project

Interview answers

What actually runs after deploying this React frontend?

Nginx serves the chosen build output. The browser runs React and the application bundle to draw the board, then fetches the existing API. Express runs separately on Node.js and the database manages stored notes. A different React rendering strategy may need a server process too. Describe the actual build before deciding what the web server must start or serve.

Why does a visit to /board/recent need an Nginx rule?

A direct visit reaches Nginx before the React entry is running. The known navigation route deliberately returns the HTML entry, and the mounted app uses the URL to choose its board heading. The asset paths and API prefix have their own rules so they cannot quietly return the same HTML.

How would you prove a note is persisted?

Verify 201 and the returned ID, then reload or request the stored collection from the same front door. Independently query the same backend and record. Check exact text and ID rather than treating a toast or a loading state as persistence evidence.

What makes an asset safe to cache for a long time?

Give its actual bytes a versioned or content-derived URL, avoid changing the contents at that URL, and keep an appropriate release retention policy. Verify referenced assets are available before publishing their HTML. Keep the API and revalidated entry policies separate.

Quick quiz

The missing JavaScript URL returns HTML with 200. Is the JS bundle deployed correctly?

No. Compare the actual body and media type with the expected generated JavaScript file. Check that the navigation fallback never catches asset URLs. An HTTP status alone cannot establish that the browser received runnable bytes.

Can a Vite client environment variable contain the MongoDB password if the app gets built privately?

Keep it on the backend only. A value embedded in JavaScript reaches the people who download it. The frontend only needs the public API path.

During MongoDB downtime the board HTML is available. Should the screen say “No notes yet”?

Show a load error. An HTTP 503 means that reading the stored list failed. A successful empty JSON array communicates a different result.

Practice tasks

  1. Read the active dist/index.html and select one exact generated script URL. Verify its body and cache header through the local Nginx entry. Request one fabricated missing asset and compare the response status and policy.
  2. Use the form from the deep URL in a local browser, reload it and compare the returned ID or note text with the real API list. Report which steps checked link routing, browser execution, API contract and storage.
  3. Plan a replacement build with a different button label. Describe when you would publish the new assets, test the candidate entry and switch traffic. Include how old cached pages would still refer to a valid script and what to verify on rollback.

Build output is deployable

Serve the selected browser artifact. Use the actual built entry to discover bundle URLs and confirm their bytes.

Fallback is a navigation choice

Known deep routes may read the same HTML. API and missing assets must follow their distinct branches.

Wait for server creation

Use the confirmed note and its ID to update the UI, and check the same record after reload.

One public origin

Keep the client's API path stable. The private proxy target and database credentials belong in server-side configuration.

Official references