Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 50 ยท Projects

Project: An Admin Dashboard with Protected Routes

Build an admin dashboard with a login page, a guard layout route, nested sections, role-based pages, return-to-page redirects and logout, plus why server checks matter.

Almost every real application has pages that only some people may open: a user's own settings, an editor's drafts, an administrator's list of users. Routing is where you decide what the person sees when they are not allowed in. A good dashboard sends visitors who are not signed in to a login page, brings them back to where they were headed after they sign in, hides links they cannot use, and shows a clear "not allowed" page when they type the address anyway.

In this project you will build exactly that: a login page, a guard implemented as a layout route, a dashboard shell with a sidebar that adapts to the user's role, three kinds of pages (open to everyone who is signed in, editors and admins, admins only) and a logout button. It applies protected routes, layout routes, redirects, nested routes and location state and return paths. React Router cannot be installed in the live editor, so the runnable code uses the small hand-written hash router from earlier lessons. It has the same shape as the library (route objects with children, Outlet, Navigate, NavLink), and real React Router code is shown as read-only snippets.

One warning belongs at the very beginning: everything a router does in the browser is user experience, not security. Anyone can open the developer tools, change a variable and render a page. Real protection happens where the data lives, on the server. The project demonstrates this on purpose in its last step.

The plan

flowchart TD
    A["Visit /dashboard/users"] --> B{"signed in?"}
    B -- no --> C["Navigate to /login?from=/dashboard/users"]
    C --> D["user logs in"]
    D --> E["Navigate to the from address"]
    B -- yes --> F{"role allowed on this page?"}
    E --> F
    F -- yes --> G["render the page"]
    F -- no --> H["render the 403 page, shell stays"]

Two separate checks: authentication (who are you) in the guard layout, and authorization (may you open this page) around individual pages.

The route tree has four branches:

flowchart TD
    R["routes"] --> I["index: redirect to /dashboard"]
    R --> L["login: LoginPage"]
    R --> G["dashboard: RequireAuth (guard layout)"]
    R --> N["path *: NotFound"]
    G --> S["DashboardLayout: sidebar, header, logout"]
    S --> O["index: Overview"]
    S --> P["reports: any signed-in user"]
    S --> C["content: editor or admin"]
    S --> U["users: admin only"]

The guard is a layout route with no UI of its own. Every page under it is protected by one piece of code, so you cannot forget a page.

Step 1: the guard and the login round trip

The core of the project is two small components. RequireAuth is a layout route: it renders an Outlet when someone is signed in and a Navigate to the login page when nobody is. It passes the address the visitor wanted in a from search parameter, so the login page can send them back. The real React Router version, as read-only code:

JSX
// RequireAuth.jsx - React Router (read-only)
import { Navigate, Outlet, useLocation } from "react-router";
import { useAuth } from "./auth";

export function RequireAuth() {
  const { user } = useAuth();
  const location = useLocation();

  if (!user) {
    const from = location.pathname + location.search;
    return <Navigate to={"/login?from=" + encodeURIComponent(from)} replace />;
  }
  return <Outlet />;
}

// in the route config
{ path: "dashboard", Component: RequireAuth, children: [ /* all protected pages */ ] }

The replace prop swaps the current history entry, so pressing Back from the login page does not return to a page that would only redirect again.

The login page does three things: it asks for credentials, calls the sign-in function and navigates to the from address on success. It must treat from as untrusted input. A link such as /login?from=//evil.example could otherwise send a freshly authenticated user to another site (an open redirect). Accept only addresses that start with a single /.

The first example is the smallest complete version: one login form, a guard and two protected pages. Use the shortcut link above the page to ask for /dashboard/settings while signed out and watch the return path work. (The stand-in Navigate only sets the hash, so it always adds a history entry; the real one takes a replace prop.)

Step 1: the guard layout and the return path

Start signed out and click the shortcut to /dashboard/settings. You land on the login page, and it announces /dashboard/settings as the destination. Sign in and you arrive at Settings, not at the generic overview. Log out and notice that you are sent to the plain /login. Logging out is a deliberate action, so there is no destination to return to.

The stand-in's navigate also tells subscribers about the new location immediately instead of waiting for the browser's asynchronous hashchange event. Without that, logging out would render the old route once with the user already gone. The real router updates its state and location together for the same reason.

Two details are worth stating. First, the guard sits in one place, so a new page added under dashboard is protected automatically. Second, the signed-in state lives in React state here, which resets on reload. A real app reads it from a session cookie, usually through a loader, as described in Authentication with Loaders and Actions.

Step 2: roles, a sidebar and the full dashboard

Now add the pieces that make it a dashboard. There are three roles: admin (everything), editor (reports and content) and viewer (reports only). The demo password for every account is demo.

  • Sidebar by role. The layout shows only the links the current role may use. This is a convenience: it saves people from clicking links that would be refused.
  • RequireRole. A wrapper element around a page. If the user's role is not in the allowed list, it renders a 403 page inside the shell instead of the page itself. Typing #/dashboard/users as a viewer therefore gives a readable message, and the sidebar is still there to move on.
  • Authorization is not authentication. The guard answers "who are you", and RequireRole answers "may you see this". Keeping them separate lets one guard protect every page while only some pages add a role rule.
  • The server check. The Overview page has a button that calls a fake admin API. The API function receives the caller and refuses anyone who is not an admin. The Users page uses the same API. If you could somehow open the Users page as a viewer, the data would still not arrive.

In the real library a role route looks like this (read-only):

JSX
// RequireRole.jsx - React Router (read-only)
import { useAuth } from "./auth";

export function RequireRole({ roles, children }) {
  const { user } = useAuth();
  if (!roles.includes(user.role)) {
    return <Forbidden />;
  }
  return children;
}

// in the route config, inside the guarded layout
{ path: "users", element: <RequireRole roles={["admin"]}><UsersPage /></RequireRole> }

With data routers you can do the same check in a loader and throw a 403 response, which is better because the page code never runs for people who may not see it.

Step 2: the dashboard with roles

Work through these scenarios:

  1. Signed out, deep link. The preview starts at /, which redirects to /dashboard, which the guard sends to the login page with from=/dashboard. Sign in as ada with the password demo. You enter the dashboard and the sidebar lists Overview, Reports, Content and Users.
  2. Wrong password. Submit a wrong password: the form shows an error and stays on the login page. The Signing in... label appears while the fake request runs.
  3. A viewer. Log out and sign in as vic. The sidebar has only Overview and Reports. Click "type /users address": the guard lets you in, because you are signed in, but RequireRole shows the 403 page inside the shell.
  4. The server check. On the Overview page click "Call the admin API". As vic the answer is 403 Forbidden: admin role required., as ada it is 200 OK - 3 users returned. This is the check that really protects data. Even if a viewer forced the Users page to render, listUsers would refuse them.
  5. An unknown section. Edit the address to #/dashboard/nothing. The * route inside the dashboard shows a not-found message with the shell intact, while #/elsewhere gives the top-level 404.

What to notice about the design

  • The guard is a layout route. One RequireAuth protects the whole subtree. New pages inherit the protection, and a missing check on one page is impossible.
  • Hiding a link is not protecting a page. The sidebar is courtesy. RequireRole is the safety net for typed addresses. The API is the real boundary.
  • replace and return paths. Redirecting with replace keeps Back working, and a from parameter restores context after login. Validating it prevents open redirects.
  • Authentication state needs a source of truth. Here it is React state. In production it is a session cookie that the server reads on every request. Use a loader to ask "who am I" before rendering, so there is no flash of the login page for signed-in users (Protected Routes and Authentication with Loaders and Actions).
  • Never trust the browser. A role stored in client state can be edited by the user. The server must derive the role from its own session record.

Extend the project

  1. Add a settings page that every role can open, and a "profile" form that the viewer cannot submit.
  2. Show a "session expired" message when the API returns 401 and send the user to login with from set.
  3. Use location.state instead of the from search parameter. What are the trade-offs when a user bookmarks the login page (useLocation and Navigation State)?
  4. Block leaving the Content page when a draft has unsaved changes (Blocking Navigation).
  5. Move the role check into a loader that throws a 403 response and render it with an error boundary (Error Boundaries and Error Elements).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the guard written as a layout route instead of a check inside each page?

    A layout route wraps all of its children with one piece of code. Checking in each page works, but you can forget it on a new page.
  2. 2. A viewer types the address of the admin Users page. Which layer shows the readable 'not allowed' message?

    RequireAuth only asks whether someone is signed in. RequireRole is the authorization step that renders the 403 page for roles that are not on the list.
  3. 3. Why is it not enough to protect the admin data with RequireRole alone?

    Everything in the browser is under the user's control. Client-side checks are a user-experience layer; the API must verify the session and the role itself.
  4. 4. What problem does validating the from parameter solve?

    An unvalidated from value like //evil.example could send a freshly signed-in user to another site. Accepting only paths that start with a single slash keeps redirects on your own site.
  5. 5. Why does the guard use replace when it redirects to the login page?

    With replace the redirecting entry is swapped for the login entry. Pressing Back then leaves the loop instead of bouncing the user back to the login page.

Summary

  • A guard is a layout route that renders Outlet for signed-in users and Navigate to /login otherwise; one guard protects the whole subtree.
  • Pass the wanted address in from, validate it (single leading slash) and return the user there after login.
  • Authentication ("who are you") and authorization ("may you open this") are separate: the guard and a RequireRole wrapper.
  • Hide links the role cannot use, but still render a clear 403 for typed addresses and let the server enforce access to data.
  • Logging out is explicit: clear the user and navigate to a plain /login.

Next: Project: A Notes App with Actions and Optimistic UI