🐙

Nextjsでの認証の記事を読んだ

2021/09/12に公開

Nextjsでの認証のタイミングがどうなのか調べた。

記事1

https://www.mikealche.com/software-development/how-to-implement-authentication-in-next-js-without-third-party-libraries

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を使う

上の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だった。

この記事を参考にしている記事が

https://qiita.com/someone7140/items/f3ffa05d3da6353af0c2

参考

記事2

https://alexsidorenko.com/blog/next-js-protected-routes/

Discussion