alephjs / aleph.js

The Full-stack Framework in Deno.

Home Page:https://alephjs.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Client side routing breaks middleware?

sudo-sand opened this issue · comments

I have an auth middleware, and checking if a request path starts with /admin and a user should have a valid cookie, else it should redirect to the home page, where the user can login.

It works great if typed the URL. If I used links, it just bypasses this middleware all together.

How to make sure the middleware is called before routing?

commented

which version are you using? the middleware should be called before routing

Im using the latest with react. It doesn't work if I use a link to navigate, but refreshing the page I get redirected if i'm not logged in.

I sat a quick demo https://github.com/sudo-sand/testing-demo I can navigate to /admin without the token cookie.

commented

since the client works as SPA, the Link can't handle the redirect response currently, however i will add support for this.

you can use a workaround like:

// ./routes/app.tsx

import { useData, useRouter } from "aleph/react";
import Header from "../components/Header.tsx";

export function data(req: Request, ctx: Context) {
  return { user: ctx.user };
}

export default function App({ children }: { children: React.ReactNode }) {
  const { data } = useData();
  const { redirect } = useRouter();
  if (!data.user) {
    redirect("/login");
    return null;
  }
  return (
    <>
      <Header />
      <code>{JSON.stringify(data)}</code>
      {children}
    </>
  );
}

then pass the user in your middleware:

  middlewares: [
    {
      name: "My Auth",
      async fetch(request, context) {
        context.user = {}
        return await context.next();
      },
    },
  ],

Thanks for that, I will use it.

It wasn't a Link component, it was a regular <a> tag