Client Middleware Redirect

This example demonstrates how client middleware can redirect by throwing a redirect(). The middleware checks for an allowed=true query parameter and redirects if it's missing.

✅ Access granted! You have the required allowed=true parameter.

Try It Out

Click the link below to navigate without the required parameter. The client middleware will intercept and redirect you back with the correct parameter.

Navigate without allowed=true →

How it works

  1. Middleware checks for allowed=true in the URL
  2. If missing, it throws redirect("/path?allowed=true")
  3. React Router intercepts the redirect and navigates
  4. The middleware runs again, this time allowing access

Example Code

import { redirect } from "react-router";
import type { MiddlewareFunction } from "@udibo/juniper";

export const middleware: MiddlewareFunction[] = [
  async ({ request }, next) => {
    const url = new URL(request.url);
    const isAuthenticated = checkAuth(); // Your auth logic

    if (!isAuthenticated) {
      throw redirect("/login");
    }

    await next();
  },
];

Note

Client middleware redirects only work during client-side navigation. For server-side redirects (initial page load), use server middleware (Hono) instead.