是否可以在 Remix.run 中设置受保护的路由,这样浏览器就无法获取受保护的源代码?

dec*_*ele 0 node.js reactjs react-router remix.run

是否可以在 Remix.run React 框架中设置受保护的路由,以便只有管理员用户才能获得受保护的组件,而普通用户根本无法将受保护的组件作为发送到浏览器的 JS 包的一部分获得?

此外,这可能需要在前端进行某种形式的代码分割。Remix.run 是否支持代码分割?

Aar*_*ers 12

这是我编写的示例应用程序中的代码片段,这是主页,只有在用户经过身份验证后才能访问。

redirect(`/login?${searchParams}`)如果用户未通过身份验证,将重定向

// Loaders provide data to components and are only ever called on the server, so
// you can connect to a database or run any server side code you want right next
// to the component that renders it.
// https://remix.run/api/conventions#loader
export let loader = async ({ request }) => {
  const redirectTo = new URL(request.url).pathname;

  let session = await getSession(request.headers.get("Cookie"));

  // if there is no access token in the header then
  // the user is not authenticated, go to login
  if (!session.has("access_token")) {
    let searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
    throw redirect(`/login?${searchParams}`);
  } else {
    // otherwise execute the query for the page, but first get token
    const { user, error: sessionErr } = await supabaseClient.auth.api.getUser(
      session.get("access_token")
    );

    // if no error then get then set authenticated session
    // to match the user associated with the access_token
    if (!sessionErr) {
      // activate the session with the auth_token
      supabaseClient.auth.setAuth(session.get("access_token"));

      // now query the data you want from supabase
      const { data: chargers, error } = await supabaseClient
        .from("chargers")
        .select("*");

      // return data and any potential errors alont with user
      return { chargers, error, user };
    } else {
      return { error: sessionErr };
    }
  }
};
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以通过在路由加载器内授权用户来保护路由,您可以决定将其重定向到其他地方或发送一个标志作为加载器数据的一部分,以便 UI 可以基于它隐藏/显示组件。

对于代码分割,Remix 在路由级别进行,但它不支持开箱即用的服务器端代码分割,您也许可以通过react-loadable 支持它。