Nextjsでの認証の記事を読んだ
Nextjsでの認証のタイミングがどうなのか調べた。
記事1
In this way, if you don’t check for authentication on the server, you can prevent adding getServerSideProps to your pages.
And if your pages don’t provide a getServerSideProps, then your site will be blazingly fast, because it will be statically rendered.
Later on the client side, you fetch the data that you need, and show a loading skeleton while it does.
getServerSideProps(HTMLをNextjs側で事前にRenderingするときの実行関数)で、認証すると表示遅くなるから、一旦表示してから、必要なデータをロードしろと書いてある。
で、Hight order componentsを使う
- [高階 (Higher-Order) コンポーネント](https://ja.reactjs.org/docs/higher-order-components.html#:~:text=高階コンポーネント (higher-order component,React における応用テクニックです。&text=具体的には、高階,返すような関数です。)
- React の Higher-order Components の利用方法
- HOC(Heigher-Order-Component)ってどうなったの?
上の2つの記事だと使いどころはもうないらしく、以下の模様。
ほとんどの場合下記のどれかでデメリット軽減で同等のものが書ける
- コンポジション(コンポーネント化)
- hooks化
で、上の記事を見返すとHOCではなく、普通にコンポジションを使っているように見えるがそれは置いておいて。
Context APIを利用して、isAuthenticated
を登録して、子要素で参照する。
それから、以下のコンポジションで、isAuthenticated
を更新する。認証されていない場合は、ローティングようコンポーネントを返す。
export const ProtectRoute = ({ children }) => {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading || (!isAuthenticated && window.location.pathname !== '/login')){
return <LoadingScreen />;
}
return children;
};
ProtectRoute
の使われ方は、HOCだった。
この記事を参考にしている記事が
参考
記事2
Discussion