Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client side routing breaks middleware? #550

Open
sudo-sand opened this issue Mar 27, 2023 · 5 comments
Open

Client side routing breaks middleware? #550

sudo-sand opened this issue Mar 27, 2023 · 5 comments

Comments

@sudo-sand
Copy link

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?

@ije
Copy link
Member

ije commented Mar 27, 2023

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

@sudo-sand
Copy link
Author

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
Copy link
Author

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

@ije
Copy link
Member

ije commented Mar 27, 2023

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

@sudo-sand
Copy link
Author

Thanks for that, I will use it.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants