♾️

react routerのLoaderFunctionを使って認証状態を判定する

に公開2件

ReactのWebアプリでURLを直打ちされたとき、認証状態を判断して、認証されていなければログイン画面にリダイレクトする処理を実装したいです。方法は色々ありそうで、ネットにも様々な方式が書かれています。うーん、それぞれのメリット・デメリットが正直肌感としてわからない...。

LoaderFunction

とりあえずLoderFunctionを使ってみることにしました。

https://api.reactrouter.com/v7/types/react_router.LoaderFunction.html

LoaderFunctionを使ったauthLoaderを定義します。

authLoader.ts
import type { LoaderFunction } from "react-router";

export const authLoader : LoaderFunction = async ({ request }) => {
    console.log("authLoaderよばれたよん" + request.url)

    //ここで認証のチェックとかできるよね

    return null;
}

ファイル構成

試した構成は次のとおりです。

react_sandbox/
|
├── app/
|    ├── auth/
|  |   └── authLoader.ts
|    ├── sub/
|    |     ├── subPage1.tsx
|    |     └── subPage2.tsx
|    ├── index.tsx
|    └── routes.ts

2種類のsubPageを用意

routes.tsではsubPageを2つ用意しました。

routes.ts
import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [
    index("index.tsx"),
    route("sub/1", "sub/subPage1.tsx"),
    route("sub/2", "sub/subPage2.tsx"),
] satisfies RouteConfig;

subPage1.tsxから呼び出されるようにclientLoaderを使って宣言。

subPage1.tsx
import { authLoader } from "~/auth/authLoader";

export const clientLoader = authLoader
clientLoader.hydrate = true;

export default function subPage1() {
    return <div>Sub Page 1</div>;
}

subPage2.tsxには定義をいれません。

subPage2.tsx
export default function subPage2() {
    return <div>Sub Page 2</div>;
}

動作結果

結果:http://localhost:5173/sub/1 にアクセス

1:211 💿 Hey developer 👋. You can provide a way better UX than this when your app is loading JS modules and/or running `clientLoader` functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback for more information.
authLoader.ts:4 authLoaderよばれたよん

結果:http://localhost:5173/sub/2
コンソール表示なし

全画面に同じ定義するのしんどい...

subPage1.tsxに入れた以下の宣言を全画面に入れれば同じauthLoaderの処理が呼び出されますが面倒です。

export const clientLoader = authLoader
clientLoader.hydrate = true;

Layoutの利用

そこで、authLayout.tsxを用意して

authLayout.tsx
import { Outlet } from "react-router";
import { authLoader } from "./authLoader";

//ここに定義
export const clientLoader = authLoader;
clientLoader.hydrate = true;

export default function authLayout() {
  // Outletが、子ルート(各画面)を表示する場所になります
  return <Outlet />;
}

そして他の画面からはclientLoaderの定義を削除します。で、routes.tsを少し変えて、layoutを利用して、auth/authLayout.tsxを適用するすべてのページを子ルートとして定義します。

routes.ts
import { type RouteConfig, index, layout, route } from "@react-router/dev/routes";

export default [
    index("index.tsx"),

    layout("auth/authLayout.tsx", [
        route("sub/1", "sub/subPage1.tsx"),
        route("sub/2", "sub/subPage2.tsx"),
    ]), 
] satisfies RouteConfig;

これでsubPage1.tsxでもsubPage2.tsxでも以下のとおり呼び出されました。なので、authLoaderに認証の処理をいれると実装が楽にできそうです。

💿 Hey developer 👋. You can provide a way better UX than this when your app is loading JS modules and/or running `clientLoader` functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback for more information.
authLoader.ts:4 authLoaderよばれたよんhttp://localhost:5173/sub/1
💿 Hey developer 👋. You can provide a way better UX than this when your app is loading JS modules and/or running `clientLoader` functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback for more information.
authLoader.ts:4 authLoaderよばれたよんhttp://localhost:5173/sub/2

React素人なのでLoaderFuctionじゃなくてXXを使うほうがいいよ、とかコメントもらえると嬉しいです(T_T)

Discussion

kwhrstrkwhrstr

loader を使うときは 認証の情報を loader で使わないのであればそれでいいような気がします
ですが実際は各 loader は独立しているので実装をしたほうがいいです

export const clientLoader = async (args: Route.ClientLoaderArgs) => {
  const auth = getAuth(args);
  if (!auth) {
    return xxx;
  }
  // ここから認証したあとの data fetch 処理
}

loader は data を取得することが前提なので SSR をつかわないで data fetch は client に任せるのであれば loader 使わずに書いてもいいと思います

1