Start learning free

LESSON 20 OF 58 · FULL-STACK: LOGIN WITH COOKIES

Routes That Need a Login

Practice

Some routes are only for a logged-in visitor: their orders, their account. Instead of writing the same login test in each of them, you write it once as a middleware: a function with req, res and next that Express runs before the route. It either answers by itself and stops, or calls next() to hand the request on to the route.

Here is a middleware for another route, one that turns visitors away while the shop is being updated:

function shopOpen(req, res, next) {
  if (process.env.MAINTENANCE === "1") {
    return res.status(503).json({ error: "Back soon" });
  }
  next();
}

app.post("/api/reviews", shopOpen, (req, res) => { … });

Express runs the functions in the order they are listed: first shopOpen, then the route, only if next() was called. The return matters: it stops the middleware right after it answers. A middleware can also put things on req for the route: requireLogin looks up the logged-in user and stores it in req.user. The route then finds the orders by req.user's email, which comes from the session, never from the request, so nobody can ask for someone else's orders.

Your server must answer:

GET /api/orders (no session)  →  401  {"error": "Login required"}
POST /api/login {"email": "ben@example.com", "password": "teapot-fan-22"}  →  200  {"email": "ben@example.com"}
GET /api/orders (Ben's cookie)  →  200  [{"id": 2, "ordered": "2026-03-15", "status": "paid"}, {"id": 6, "ordered": "2026-05-21", "status": "cancelled"}]

On the page, the given Orders page shows "Login required" to a visitor who isn't logged in. After Ana logs in, it lists Order 1, 2026-03-02: paid and Order 3, 2026-04-05: paid.

Your task: in server/app.js, below the session middleware, write requireLogin: 401 {"error": "Login required"} when the session has no userId, otherwise the user's id and email in req.user and next(). Below the logout route, add GET /api/orders with requireLogin in front, answering the id, date and status of that user's orders.


Assignment
Follow the Coding Tutorial to write the requireLogin middleware and the orders route that uses it.


Hint
The orders table has a customer_id, and the customers table has the email: join them and keep the rows WHERE customers.email = ?, ordered by the order's id.


STEP 1 OF 8
    Ctrl + Enter to check