{}const=>[]async()letfn</>var
Development

React Router 7.9: Middleware without pain

How to embed authorization and data preloading directly into routes without crutches. A new level of convenience in React Router 7.9!

К

Kodik

Author

3 min read

React Router has long been the standard for routing in the React world. But the version 7.9 brought what many had been waiting for for years — Middleware API. Now you can embed access checks, data preloading, and other "layers" directly into routes, without unnecessary crutches.

What is Middleware in React Router?

If earlier it was necessary to build useEffect, contexts or wrap routes in HOC, now everything is solved elegantly:

  • Access checks (e.g. user role)

  • Redirects (if not authorized — to the login page)

  • Loading data before page rendering

  • Logging and metrics

Middleware are functions that are performed before component render, and can either allow the transition or change it.

🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

Example: authorization check


import { createBrowserRouter, RouterProvider } from "react-router";
import App from "./App";
import Dashboard from "./pages/Dashboard";
import Login from "./pages/Login";

const requireAuth = async ({ context, next }) => {
  if (!context.user) {
    return Response.redirect("/login");
  }
  return next();
};

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    children: [
      {
        path: "dashboard",
        element: <Dashboard />,
        middleware: [requireAuth]
      },
      {
        path: "login",
        element: <Login />
      }
    ]
  }
]);

export default function Root() {
  return <RouterProvider router={router} />;
}
  

Now route protection is built into the router itself - no need to reinvent the wheel.

Preloading data before rendering


const preloadUser = async ({ next }) => {
  const user = await fetch("/api/me").then(r => r.json());
  return next({ context: { user } });
};

const router = createBrowserRouter([
  {
    path: "/profile",
    element: <Profile />,
    middleware: [preloadUser]
  }
]);
  

Now in the Profile component, the data will be available immediately, without the "Loading..." flashing.

Comparison with previous approaches

1. HOC (Higher-Order Components)


function withAuth(Component) {
  return function Wrapped(props) {
    const user = useUser();
    if (!user) return <Navigate to="/login" />;
    return <Component {...props} />;
  }
}
  

❌ Cons: code duplication, more difficult to manage data streams, component nesting increases.

2. useEffect + Navigate


function Dashboard() {
  const user = useUser();
  const navigate = useNavigate();

  useEffect(() => {
    if (!user) navigate("/login");
  }, [user]);

  return <div>Dashboard</div>;
}
  

❌ Cons: first the component is mounted, then the redirect comes — users see "flashing".

3. Middleware API (new approach)

✅ Everything is in the route, without "flashing", readable and centralized code.

Why is it cool?

  • Cleaner code — routes become a single point for access and download logic.

  • Faster UX — preloading data before rendering.

  • Flexibility — you can write your own middleware for any needs (logging, analytics, feature flags).

But! Middleware works asynchronously, so with a large number of checks, it is worth thinking about performance and caching the results.

React Router 7.9 did what was expected of it: it turned routing into central access and data management locationMiddleware API opens the way to more predictable and accurate applications.

In Codice we make programming training simple and easy to understand: courses in Go, JavaScript, Python and other technologies — all in one application.

And we also have a cozy Telegram channel, where we discuss the latest news from the world of development, share insights and analyze new features together. Join usto learn and grow in IT with like-minded people!

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card