aleph.js icon indicating copy to clipboard operation
aleph.js copied to clipboard

Client side routing breaks middleware?

Open sudo-sand opened this issue 2 years ago • 5 comments
trafficstars

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?

sudo-sand avatar Mar 27 '23 03:03 sudo-sand

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

ije avatar Mar 27 '23 04:03 ije

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.

sudo-sand avatar Mar 27 '23 04:03 sudo-sand

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

sudo-sand avatar Mar 27 '23 04:03 sudo-sand

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();
      },
    },
  ],

ije avatar Mar 27 '23 10:03 ije

Thanks for that, I will use it.

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

sudo-sand avatar Mar 27 '23 18:03 sudo-sand