REST APIs, Middleware, CORS, and Secrets
Module 3 · Going Full-Stack

REST APIs, Middleware, CORS, and Secrets

Inside the application tier: HTTP methods and status codes, REST routes, Express's middleware pipeline, schemas with an ODM, cross-origin rules, environment variables, and how the frontend fetches data with loading states.

Speaking HTTP

The phone and the server talk using HTTP, the request–response protocol of the web. Every exchange has the same parts:

  • A method saying what kind of action is requested — GET (read), POST (create or submit), PUT/PATCH (update), DELETE (remove).
  • A URL path naming the resource — /movies.
  • Headers carrying metadata — content type, authorization, origin.
  • An optional body — usually JSON for POST requests.

The server answers with a status code and usually a body:

CodeMeaningExample in the movie app
200 OKIt workedThe movie list came back
400 Bad RequestThe client sent something invalidA required field was missing
404 Not FoundNo such resourceA misspelled path
500 Internal Server ErrorThe server failedThe database connection broke

REST APIs

An API (application programming interface) is a contract for how one program asks another for something. A REST API organizes that contract around resources identified by URLs and manipulated with standard HTTP methods. GET /movies means “give me the movies collection.” It’s simple, predictable, and works with any client that speaks HTTP — browser, phone, or another server.

The first version of the movie API has two routes:

  • GET / — a health check that answers with a short message, so you can confirm the server is up.
  • GET /movies — fetches movies from the database and returns them as JSON.

Express and the Middleware Pipeline

Express handles each incoming request by passing it through a chain of middleware — small functions that each get a chance to inspect the request, modify it, respond, or hand it to the next function. Route handlers are simply the last middleware in the chain.

  1. 1 CORS

    add cross-origin headers

  2. 2 Parse body

    turn JSON into an object

  3. 3 Log

    record method, path, status

  4. 4 Ensure DB

    connect if not connected

  5. 5 Route handler

    query, then send JSON

Middleware is where cross-cutting concerns live — things every request needs, written once. The movie API uses one especially instructive pattern: a connection middleware that checks a flag, connects to MongoDB only if not already connected, and returns a 500 error if the connection fails. Putting it in front of database routes means no handler ever queries a database that isn’t there.

Schemas and ODMs

MongoDB doesn’t require a schema, but applications benefit from one. An ODM (object–document mapper) such as Mongoose lets you declare the shape of a document — a title is a string, genres is a list of strings, year is a number — and gives you a model to query with. A schema at the application layer catches malformed data before it reaches the database, and it documents what the data looks like for the next developer.


CORS: Who Is Allowed to Ask?

Browsers enforce the same-origin policy: a page loaded from one origin (scheme + host + port) can’t freely read responses from a different origin. This protects users — a malicious site can’t silently read your bank’s API using your logged-in session.

CORS (Cross-Origin Resource Sharing) is how a server opts in to cross-origin requests. The server sends headers like Access-Control-Allow-Origin stating which origins may read its responses. The browser checks them; if the origin isn’t allowed, the browser blocks the response.

Two facts trip people up:

  • CORS is enforced by browsers, not servers. Native mobile apps and command-line tools ignore it. It protects browser users; it is not an access-control mechanism for your API.
  • The default in many tutorials allows every origin. That’s fine for a public, read-only movie list. For an API that uses cookies or returns private data, list the exact origins you trust.

Secrets and Environment Variables

The database connection string from the last lesson contains a password. It must never be written into source code. Instead, apps read configuration from environment variables — key–value settings provided by the environment the program runs in:

# .env  (never committed)
MONGODB_URI=mongodb+srv://app-user:********@cluster.example.net/movies
PORT=3000

During development, a library like dotenv loads a .env file into the process’s environment. Two habits make this safe:

  1. Add .env to .gitignore so it is never committed.
  2. Commit an example.env with the variable names and placeholder values, so others know what to set.

The server should also fail fast: if MONGODB_URI is missing at startup, print a clear error and exit, rather than starting up and failing mysteriously on the first request.

The frontend uses environment variables too — for example API_URL, the address of the backend. Remember Module 2’s rule: frontend variables end up in the app bundle, so they may hold addresses but never secrets.


The Frontend Side: Fetching Data

With data on a server, the app must fetch it, which introduces side effects — work outside of rendering. React’s useEffect hook runs side effects after render:

useEffect(() => {
  fetchMovies();   // runs once when the screen first appears
}, []);

The empty array is the dependency list: “run once, on mount.” A second effect with [searchTerm, movies] re-filters whenever either changes.

Network requests take time, so the app tracks a loading state and shows a spinner (ActivityIndicator) until data arrives. A real app also tracks an error state, because networks fail.

⚠️ Common Pitfall: Reading an HTML Error Page as JSON

Common mistake: seeing JSON Parse error: Unexpected character: < and assuming the API code is broken.

That < is the first character of an HTML page. The app asked for JSON but received HTML — often a sign-in or warning page from a private forwarded port, a proxy error page, or a 404 page. The fix is upstream: make sure the URL is right, the port is reachable, and check the response’s status code and content type before parsing. A trailing slash in API_URL that turns /movies into //movies causes the same symptom.

🧠 Knowledge Check

1. Which status code best fits 'the database connection failed while handling the request'?

2. Why does CORS NOT protect your API from a script running outside a browser?

3. What is middleware in Express?

4. Which pair of habits keeps environment-variable secrets out of a repository while staying helpful to teammates?


Up Next

The app is now a real full-stack system — which means more code, more contributors, and more ways for a change to break something or open a hole. Module 4 introduces DevSecOps: automating testing and security checks so they happen on every change.