Logging out has to happen on the server. If only the browser forgot the token, anyone who had copied it could still use it. So POST /logout deletes the request's token from the tokens table. After that the shop doesn't know that token, and it gets 401 everywhere.
To delete the token, the route needs the token itself, not just the user: a user who logged in twice has two tokens. So the lines that find it (the header first, then the session) move into a function of their own, currentToken(req: Request): string, which both currentUser(req) and the /logout route call.
A DELETE is a query like the others: prepare it, then run it with the values. For example, a route that empties a user's cart could run:
db.prepare("DELETE FROM cart_items WHERE user_id = ?").run(req.user.id);
In the tests, Ana logs in twice: first on her phone (token <phone>, sent in the header), then in the browser (token <token>, also kept in the session that the browser's cookie leads to). Logging out in the browser must not log the phone out:
GET /me (cookie) → 200 {"email": "ana@example.com", "id": 2, "role": "customer"}
POST /logout (cookie) → 200 {"message": "Logged out"}
GET /me (cookie) → 401 {"error": "Login required"}
GET /me (Bearer <token>) → 401 {"error": "Login required"}
GET /me (Bearer <phone>) → 200 {"email": "ana@example.com", "id": 2, "role": "customer"}
POST /logout (Bearer <phone>) → 200 {"message": "Logged out"}
GET /me (Bearer <phone>) → 401 {"error": "Login required"}
Your task: move the token-finding lines into currentToken(req), rewrite currentUser(req) on top of it, and add POST /logout behind loginRequired: it deletes this request's token, destroys the session with req.session.destroy(() => {}) and answers { message: "Logged out" }.
Assignment
Follow the Coding Tutorial to add a /logout route that really logs the user out.
Hint
Delete the token before you call req.session.destroy(() => {}): currentToken(req) reads the session. In TypeScript, destroy needs a function to call when it's done; an empty () => {} is enough. loginRequired has stored the user in req.user, but this route doesn't need it.
Free plan: 30 tutor messages. PRO is unlimited.
