Remix.run 中是否有可能存在受保护的路由,因此浏览器无法获取受保护的源代码?

Is it possible to have protected routes in Remix.run, so the browser doesn't get the protected source code?

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

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

您可以通过在路由的加载程序中授权用户来保护路由,在那里您可以决定将其重定向到其他地方或发送一个标志作为加载程序数据的一部分,这样 UI 可以 hide/show 基于它的组件。

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

这是来自 sample app I wrote 的代码片段,这是主页,只有在用户通过身份验证后才能访问。

如果用户未通过身份验证,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 };
    }
  }
};