Closed7
React Router v7 middlewareを使ってみる

- .changesetの中にmiddlewareを解説するmdがあり、これを読むのが良さそう
https://github.com/remix-run/react-router/pull/12941/files#diff-921bfd5065e6581454d9d5ad1c25bc3cf9a57cb8d7df17078618e118083b2d41 -
react-router.config.ts
に Future flagを立てる必要がある- Reacr Router v7 の official docsには書いてない
- 型情報の生成は Router Moduleのため
react-router typegen
で関数の方が生成される - .changesetには
declare module
する必要があるように書かれているがなくても型は生成される

.changesetにはdeclare moduleする必要があるように書かれているがなくても型は生成される
結果的には嘘、ContextがAppLoadContextとして認識されてしますのでしっかりと記述する必要がある

- changesetを読む限りでは、root.tsxだけでなくroute moduleで動きそう
- RemixのRFCでは、
root.tsx
で使うことを想定していたっぽいけど React Router v7 ではroot.tsx = route module
なので問題なさげ - https://github.com/remix-run/remix/discussions/7642
- RemixのRFCでは、
- 以下を書くだけ
-
unstable_
のprefixがないと動かない。(いつはがれる?BCになりそうで怖い
-
export const unstable_middleware = [serverLogger, serverAuth]; // server
export const unstable_clientMiddleware = [clientLogger]; // client

- middleware内で
redirect
をthrow
すると全ての処理を破棄してリダイレクトできる- 認証系ではこっちを使うのが良さそう

.changesetの110行目あたりのここ多分typoってる. nextは第二引数でとる
```tsx
const redirects: Route.unstable_MiddlewareFunction = async ({
request,
next,
}) => {

const res = await next()
は必須ではない。Response
をいじって返したい時だけ(CookieとかSession とかかな)

- route matchをしたいときはlayoutから呼ぶ
- layoutでなくてもroute moduleであればmiddlewareが呼び出しできる
- なのでTypedRoutesの恩恵を受ける
このスクラップは2ヶ月前にクローズされました