EthicsComputerCourses
Join training +91 90532 10052

Login, Protected Routes & Sessions

MERN Stack · Lesson 13 of 20 Intermediate 12 min read Updated

By the end of this lesson TaskBoard will have a proper login page instead of the DevTools trick. The app will ask the API "who am I?" when it loads, keep visitors who are not signed in away from the board, send them back to the page they wanted after login, and notice when a session ends, whether it expired after two hours or was closed in another tab. Admins will also see a "Delete task" button that teachers do not.

What you should know first: Authentication with JWT & Cookies, which built the login, logout and me routes and the HttpOnly cookie, and Routing with React Router for the route table. React Context is taught in Context in the React course. Versions checked: React 19.3.1, react-router 8.5.1 and the Express 5.3.0 API from the earlier lessons. Every result below comes from a real Chrome session.

Who knows that you are signed in?

The JWT sits in an HttpOnly cookie, so React cannot read it. That is the point: an XSS bug cannot steal it. But it raises a question: how does the React app know who is signed in?

It asks. Think of a hotel key card. The card itself does not show your name or room; the front desk looks it up. When TaskBoard loads, it calls GET /api/auth/me. The browser attaches the cookie, and the API answers with the user or with 401. The answer lives in React state for as long as the page is open.

The app moves through three states:

StatusMeaningWhat the screens do
checking/me has not answered yetShow "Checking your session..."
signed-in/me (or login) returned a userShow the app, the user's name and Log out
signed-out/me said 401, the user logged out, or a request found the session goneSend protected pages to /login

The checking state matters. Without it, a refresh would flash the login page for a moment and redirect a signed-in teacher away from the task she had open.

Step 1: The auth API and a 401 alarm

Create client/src/api/auth.js with one function per auth route:

JavaScript
import { apiRequest } from "./client.js";

export function login({ email, password }) {
  return apiRequest("/api/auth/login", { method: "POST", body: { email, password } });
}

export function logout() {
  return apiRequest("/api/auth/logout", { method: "POST" });
}

export function getMe({ signal } = {}) {
  return apiRequest("/api/auth/me", { signal });
}

A session can end while the app is open: the token expires after two hours, or the teacher logs out in another tab, which clears the cookie for every tab. The next request then gets 401. apiRequest sees every reply, so it is the right place for an alarm. Add this to client/src/api/client.js:

JavaScript
// AuthProvider registers what to do when a request finds the session gone.
let onUnauthorized = () => {};
export function setUnauthorizedHandler(handler) {
  onUnauthorized = handler;
}

// ...inside apiRequest, in the !res.ok branch, before the throw:
// A 401 from login or me is normal; from any other route it means the session has ended.
if (res.status === 401 && !path.startsWith("/api/auth/")) onUnauthorized();

The /api/auth/ exception is important. A wrong password returns 401 from login, and a visitor with no cookie gets 401 from /me. Neither means "your session just ended".

Step 2: An AuthProvider for the whole app

Context lets any component read a value without passing props through every level. Put the context and its hook in client/src/hooks/useAuth.js:

JavaScript
import { createContext, useContext } from "react";

export const AuthContext = createContext(null);

// { status: "checking" | "signed-in" | "signed-out", user, notice, login, logout }
export function useAuth() {
  const auth = useContext(AuthContext);
  if (!auth) throw new Error("useAuth must be used inside <AuthProvider>");
  return auth;
}

Then the provider, client/src/components/AuthProvider.jsx. It owns the state from the table above:

React JSX
import { useEffect, useMemo, useState } from "react";
import { getMe, login as apiLogin, logout as apiLogout } from "../api/auth.js";
import { setUnauthorizedHandler } from "../api/client.js";
import { AuthContext } from "../hooks/useAuth.js";

const SIGNED_OUT = { status: "signed-out", user: null, notice: "" };

export default function AuthProvider({ children }) {
  const [state, setState] = useState({ status: "checking", user: null, notice: "" });

  // On page load, ask the API who the cookie belongs to.
  useEffect(() => {
    const controller = new AbortController();
    getMe({ signal: controller.signal })
      .then((user) => setState({ status: "signed-in", user, notice: "" }))
      .catch((error) => {
        if (error.name !== "AbortError") setState(SIGNED_OUT);
      });
    return () => controller.abort();
  }, []);

  // Any later 401 means the session expired or was ended in another tab.
  useEffect(() => {
    setUnauthorizedHandler(() =>
      setState({ status: "signed-out", user: null, notice: "Your session has ended. Please log in again." })
    );
    return () => setUnauthorizedHandler(() => {});
  }, []);

  const value = useMemo(
    () => ({
      ...state,
      async login(email, password) {
        const user = await apiLogin({ email, password });
        setState({ status: "signed-in", user, notice: "" });
      },
      async logout() {
        await apiLogout().catch(() => {}); // forget the user here even if the server is unreachable
        setState(SIGNED_OUT);
      },
    }),
    [state]
  );

  return <AuthContext value={value}>{children}</AuthContext>;
}

In React 19 you can render <AuthContext> directly as the provider; older code writes <AuthContext.Provider>. Logging out must go through the API, because only the server can clear an HttpOnly cookie. In main.jsx, wrap <App /> in <AuthProvider>, inside <BrowserRouter>.

Step 3: Guard the routes

A protected route is a page that only signed-in users may see. Create client/src/components/RequireAuth.jsx. Like Layout, it renders an <Outlet />, so it can wrap a whole group of routes:

React JSX
import { Navigate, Outlet, useLocation } from "react-router";
import { useAuth } from "../hooks/useAuth.js";

// Wraps routes that need a login. Remembers where the user wanted to go.
export default function RequireAuth() {
  const { status } = useAuth();
  const location = useLocation();

  if (status === "checking") return <p>Checking your session...</p>;
  if (status === "signed-out") return <Navigate to="/login" replace state={{ from: location }} />;
  return <Outlet />;
}

<Navigate> redirects as soon as it renders. replace swaps the history entry, so the Back button does not bounce the user into the guard again. state={{ from: location }} carries the wanted address to the login page. Now App.jsx:

React JSX
<Routes>
  <Route element={<Layout />}>
    <Route path="login" element={<LoginPage />} />
    <Route element={<RequireAuth />}>
      <Route index element={<BoardPage />} />
      <Route path="tasks/new" element={<NewTaskPage />} />
      <Route path="tasks/:id" element={<TaskPage />} />
    </Route>
    <Route path="*" element={<NotFoundPage />} />
  </Route>
</Routes>

Because the guard handles signed-out visitors, delete the error?.status === 401 branch from BoardPage; it can no longer happen.

Step 4: The login page

Create client/src/pages/LoginPage.jsx:

React JSX
import { useState } from "react";
import { Navigate, useLocation } from "react-router";
import { useAuth } from "../hooks/useAuth.js";

export default function LoginPage() {
  const { status, notice, login } = useAuth();
  const location = useLocation();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const from = location.state?.from;
  const target = from ? from.pathname + from.search : "/";
  if (status === "signed-in") return <Navigate to={target} replace />;

  async function handleSubmit(event) {
    event.preventDefault();
    setError("");
    setSubmitting(true);
    try {
      await login(email, password); // status becomes "signed-in", and the line above redirects
    } catch (err) {
      setError(err.details?.length ? err.details.map((d) => d.message).join(". ") : err.message);
      setPassword("");
      setSubmitting(false);
    }
  }

  return (
    <section className="login">
      <h2>Log in</h2>
      {notice && !error && <p role="status">{notice}</p>}
      {error && <p role="alert">{error}</p>}
      <form className="task-form" onSubmit={handleSubmit}>
        <label htmlFor="email">Email</label>
        <input id="email" type="email" autoComplete="username" required value={email}
          onChange={(e) => setEmail(e.target.value)} />
        <label htmlFor="password">Password</label>
        <input id="password" type="password" autoComplete="current-password" required value={password}
          onChange={(e) => setPassword(e.target.value)} />
        <button type="submit" disabled={submitting || status === "checking"}>
          {submitting ? "Logging in..." : "Log in"}
        </button>
      </form>
    </section>
  );
}

A few details are about security and comfort:

  • autoComplete="username" and "current-password" let password managers fill the form, which encourages long, unique passwords.
  • After a failed attempt the password box is cleared, but the email stays.
  • The error is whatever the server said. For a wrong email and for a wrong password it is the same "Email or password is incorrect", so the page reveals nothing about who has an account.
  • target comes from router state, which only TaskBoard's own code can set. If you ever accept a return address from the query string, such as /login?next=..., allow only paths that start with / and not //. Otherwise an attacker's link could send people to a fake site after a real login. This trick is called an open redirect.

Finally, the header. In components/Header.jsx, read useAuth(). When signed in, show the menu, the user's name and role, and <button type="button" onClick={logout}>Log out</button>; otherwise show only the centre's name.

Step 5: Watch it work

Here is a real Chrome session, starting with no cookie and a bookmarked task:

Output
Open /tasks/6afac2073df1de4286056426     -> redirected to /login (GET /api/auth/me 401)
Priya, wrong password                    -> "Email or password is incorrect", password box emptied
Priya@Example.com, correct password      -> back on /tasks/6afac2073df1de4286056426
                                            header: Priya Sharma (teacher) Log out; no Delete button
Refresh the page                         -> GET /api/auth/me 200, still signed in; document.cookie is ""

Next, a session ending under the user's feet. With the board open at /?status=doing, we logged out through the API from the console, exactly what another tab's "Log out" button does. Then we clicked "Move to Done":

Output
PATCH /api/tasks/6afac2073df1de4286056426 -> 401
Screen: /login  "Your session has ended. Please log in again."
Kabir logs in                             -> back on /?status=doing, header: Kabir Malik (admin) Log out

The 401 set off the alarm, the guard redirected, and the saved from brought Kabir back to the same filtered board. A token that expires after two hours ends the same way, because requireAuth on the server answers 401 for it too. Kabir then opened a task and saw "Delete task". He confirmed the browser's question, the API answered 204, and the app returned to the board without that task.

Hiding buttons is not security

TaskPage shows the delete button only to admins:

React JSX
const { user } = useAuth();
// ...
{user.role === "admin" && (
  <button type="button" onClick={remove}>
    Delete task
  </button>
)}

That is good manners: teachers do not see a button that would only fail. But it protects nothing. Priya can still type fetch("/api/tasks/...", { method: "DELETE" }) in the console. The real lock is requireRole("admin") on the server, which answered her with 403 in the JWT lesson. The demo below shows both layers. The "server" here is a fake that checks the role like TaskBoard's API.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const USERS = { priya: { name: "Priya Sharma", role: "teacher" }, kabir: { name: "Kabir Malik", role: "admin" } };

// Fake API: the role check lives here, whatever the UI shows.
function fakeDelete(user) {
  return new Promise((resolve) => setTimeout(() => {
    resolve(user.role === "admin" ? "204 No Content: task deleted" : '403 {"error":{"message":"You do not have permission to do this"}}');
  }, 400));
}

function Demo() {
  const [who, setWho] = useState("priya");
  const [log, setLog] = useState([]);
  const user = USERS[who];
  const send = async (how) => {
    const reply = await fakeDelete(user);
    setLog((l) => [...l.slice(-3), `${user.name} via ${how}: ${reply}`]);
  };
  return (
    <div>
      <label>Signed in as <select value={who} onChange={(e) => setWho(e.target.value)}>
        <option value="priya">Priya (teacher)</option><option value="kabir">Kabir (admin)</option>
      </select></label>
      <h3>Print Class 10 maths worksheets</h3>
      {user.role === "admin" && <button onClick={() => send("the Delete button")}>Delete task</button>}
      <p><button onClick={() => send("the console")}>Send DELETE from the console anyway</button></p>
      <pre>{log.join("\n")}</pre>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<Demo />);

As Priya there is no "Delete task" button, but "Send DELETE from the console anyway" gets 403. Switch to Kabir: the button appears, and both ways get 204.

See a session expire

This demo puts the whole flow in one file: a fake API whose session lasts 20 seconds, a guard, a login page and a return to the page you wanted. Real React Router is not available in this editor, so a page state plays the router and also remembers where you wanted to go.

React JSXOpen in editor
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

// Fake API with a 20-second session.
const server = { expires: 0 };
const api = {
  login: (pw) => new Promise((ok, fail) => setTimeout(() => {
    if (pw !== "rohtak-chalk-2026") return fail(new Error("Email or password is incorrect"));
    server.expires = Date.now() + 20000;
    ok({ name: "Priya Sharma" });
  }, 300)),
  getTask: () => new Promise((ok, fail) => setTimeout(() => {
    if (Date.now() > server.expires) { const e = new Error("Please log in"); e.status = 401; return fail(e); }
    ok({ title: "Print Class 10 maths worksheets", status: "todo" });
  }, 300)),
  endSession: () => { server.expires = 0; },
};

function App() {
  const [user, setUser] = useState(null);
  const [page, setPage] = useState("task"); // the page the user asked for
  const [notice, setNotice] = useState("");
  const [left, setLeft] = useState(0);

  useEffect(() => {
    const t = setInterval(() => setLeft(Math.max(0, Math.round((server.expires - Date.now()) / 1000))), 500);
    return () => clearInterval(t);
  }, []);

  const signedOut = (message) => { setUser(null); setNotice(message); };
  // The guard: no user, no page. "page" keeps the wanted address for after login.
  if (!user) return <Login notice={notice} onDone={(u) => { setUser(u); setNotice(""); }} />;
  return (
    <div>
      <p>Signed in as {user.name}. Session ends in {left} s. <button onClick={api.endSession}>Log out in another tab</button></p>
      <p><button onClick={() => setPage("board")}>Board</button> <button onClick={() => setPage("task")}>Task page</button></p>
      {page === "task" ? <TaskPage onUnauthorized={signedOut} /> : <p>The board (pretend).</p>}
    </div>
  );
}

function TaskPage({ onUnauthorized }) {
  const [text, setText] = useState("Press Load to call GET /api/tasks/:id");
  const load = () => api.getTask()
    .then((t) => setText(`${t.title} (${t.status})`))
    .catch((e) => (e.status === 401 ? onUnauthorized("Your session has ended. Please log in again.") : setText(e.message)));
  return <div><h3>Task page</h3><p>{text}</p><button onClick={load}>Load</button></div>;
}

function Login({ notice, onDone }) {
  const [pw, setPw] = useState("");
  const [error, setError] = useState("");
  const submit = (e) => { e.preventDefault(); api.login(pw).then(onDone).catch((err) => { setError(err.message); setPw(""); }); };
  return (
    <form onSubmit={submit}>
      <h3>Log in</h3>
      {notice && <p>{notice}</p>}{error && <p style={{ color: "crimson" }}>{error}</p>}
      <label>Password <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} /></label>
      <button>Log in</button>
      <p>Hint: rohtak-chalk-2026</p>
    </form>
  );
}

createRoot(document.getElementById("root")).render(<App />);

You start on the login page, because you asked for the task page while signed out. Log in and you land on the task page, not the board. Press "Load": it works. Press "Log out in another tab", then "Load" again: the 401 sends you to the login page with "Your session has ended", and logging in brings you back to the task page.

Common mistakes

  • Redirecting before /me answers. Without a checking state, every refresh flashes the login page and loses the address.
  • Treating every 401 the same. A failed login is not an expired session; exclude the auth routes from the alarm.
  • Logging out only in React. JavaScript cannot delete an HttpOnly cookie; call POST /api/auth/logout.
  • Hiding buttons instead of checking roles on the server. UI checks are for comfort; requireRole is the lock.
  • Return addresses from the query string without checks. That creates an open redirect; accept only same-site paths.
  • Keeping the user in localStorage. It can disagree with the server; ask /me.

Interview questions

1. How does a React app know who is logged in if the token is in an HttpOnly cookie?

It asks the server. On load it calls an endpoint such as GET /api/auth/me; the browser sends the cookie automatically, and the server replies with the user or 401. The result is kept in React state, usually in a context provider.

2. How do you implement a protected route with React Router?

Wrap the protected routes in a layout-style component that reads the auth state. While the session check runs it shows a loading message; if signed out it renders <Navigate to="/login" replace state={{ from: location }} />; otherwise it renders <Outlet />. After login, the app navigates to the saved from address.

3. What happens in your app when a session expires while the user is working?

The next API call returns 401. The fetch wrapper calls a handler registered by the auth provider, which marks the user as signed out with a message. The route guard then redirects to the login page, remembering the current address, so the user returns to the same place after logging in again.

4. What is an open redirect, and how can a login page cause one?

It is a page that sends users to any address given in a parameter, such as /login?next=https://evil.example. After a genuine login the user lands on a fake site that can ask for the password again. Accept only relative paths beginning with a single /, or keep the return address in router state.

Key points

  • React cannot read the HttpOnly cookie; AuthProvider calls GET /api/auth/me on load and keeps checking, signed-in or signed-out in context.
  • RequireAuth shows a message while checking, redirects signed-out users to /login with state.from, and otherwise renders <Outlet />.
  • The login page redirects to from after success and shows the server's generic error on failure.
  • apiRequest reports any 401 outside /api/auth/, so expired sessions and other-tab logouts lead back to the login page.
  • Logout calls the API, because only the server can clear the cookie.
  • Role checks in the UI are for comfort; the server's requireRole is the real protection.

Exercise

Add an admin-only "Staff" page at /staff that lists every user's name and role, using the existing useUsers hook. Write a reusable RequireRole component that renders <Outlet /> for the right role and a "You do not have permission" message otherwise, and nest the route inside it. Check that Priya sees the message without any /api/users request, and Kabir sees the list.

Show solution
React JSX
// components/RequireRole.jsx
import { Outlet } from "react-router";
import { useAuth } from "../hooks/useAuth.js";

// Use inside <RequireAuth>, so user is never null here.
export default function RequireRole({ role }) {
  const { user } = useAuth();
  if (user.role !== role) return <p role="alert">You do not have permission to see this page.</p>;
  return <Outlet />;
}

// pages/StaffPage.jsx
import { useUsers } from "../hooks/useUsers.js";

export default function StaffPage() {
  const users = useUsers();
  return (
    <section>
      <h2>Staff</h2>
      <ul>
        {users.map((u) => (
          <li key={u.id}>
            {u.name} ({u.role})
          </li>
        ))}
      </ul>
    </section>
  );
}

// App.jsx, inside the <RequireAuth> group
<Route element={<RequireRole role="admin" />}>
  <Route path="staff" element={<StaffPage />} />
</Route>
Output
Priya opens /staff: "You do not have permission to see this page." (no /api/users request)
Kabir opens /staff: Staff / Kabir Malik (admin) / Priya Sharma (teacher)

RequireRole sits inside RequireAuth, so it never sees a signed-out user. The page is hidden from teachers for comfort; if the staff list ever shows private data, the API route itself must also use requireRole("admin").

Quick Quiz

1. Why does AuthProvider start in a checking state instead of signed-out?

2. A teacher's request to PATCH /api/tasks/:id returns 401. What does TaskBoard do?

3. Why must logout call POST /api/auth/logout?

4. The delete button is shown only to admins. Is that enough to stop teachers deleting tasks?

Learn MERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call