Skip to content

React Router v7での認証とセッション管理

This content is a draft and will not be included in production builds.

remix-authremix-auth-oauth2 でGoogle認証する。認証できれば idToken を得られるので、これを使ってセッション管理をする。

CookieにJWTを入れて管理する。セッションが有効かどうかはCloudflare KVを使う?

JWTはConnectのヘッダに入れてサーバで検証する。

今の時点では、すべての loaderaction で個別にセッション確認を実装する必要がある。Remix時代のFAQにはHow can I have a parent route loader validate the user and protect all child routes?という項目があって、以下のコードが紹介されていた。

const { getSession } = createCookieSessionStorage();
export function requireUserSession(request: Request): Promise<void> {
const cookie = request.headers.get("cookie");
const session = await getSession(cookie);
if (!session.has("userId")) {
throw redirect("/login");
}
}

上記の関数を loader で使う。

export async function loader({ request }: LoaderFunctionArgs) {
await requireUserSession(request);
}

React Router v7の計画にはミドルウェアの実装が入っているけれど、まだないので個別に書くしかない。しかし面倒なので、Best practice around authentication checks in nested routesの例を真似して実装するといい。

function withAuth(loader: LoaderFunction) {
return async (args) => {
return loader(args)
}
}
export const loader = withAuth(async ({ request }) => {
...
})