LoginSignup
7
4

More than 1 year has passed since last update.

Nuxt.jsのSSRをざっくり理解したい

Last updated at Posted at 2022-06-29

こんにちは。駆け出しフロントエンドです。

Nuxt.jsのSSRを使用しているページで挙動がいまいちわかっていなかったので、まとめてみました。

SSRとは

Nuxt.jsの公式から翻訳&引用です。

サーバー側レンダリング(SSR)は、ブラウザーでWebページをレンダリングする代わりに、サーバー上にWebページを表示することによって貢献するアプリケーションの機能です。

これを読んでもピンときませんよね。SSRとはガチャか何かのランクなのでは??と思う方もいらっしゃると思います。(私がそうでした)
SSRって何?という方は以下の記事が図解もあり、わかりやすかったのでおすすめです。

SSRの挙動

結論から言ってしまうと、SSRの挙動は以下です。

  • サーバーからロードされる時はサーバーサイドレンダリング(初回またはブラウザでURL直接指定の時)
  • ロードされた以降はクライアントサイドレンダリング(リロード時など)

SSRになった場合とCSRになった場合はcookieの取扱なども変わるので、どちらでも問題なく表示・バグがないように作らないといけません。

Nuxt.jsのライフサイクル

※イメージはNuxt.jsのライフサイクル覚書より拝借しました🙇‍♀️
20190529112056.png

asyncDataについて

asyncDataはページコンポーネントの初期化前に呼び出される関数のことで、「pages」ディレクトリ配下のコンポーネントのみ使用できます。

コンポーネント内ではasyncDataを使用できないため、値を渡したい場合はpropsとして渡すなど工夫が必要のようです。

  1. Use the new fetch hook that is available in Nuxt 2.12 and later versions.
  2. Make the API call in the mounted hook and set data properties when loaded. Downside: Won't work for server side rendering.
  3. Make the API call in the asyncData method of the page component and pass the data as props to the sub components. Server rendering will work fine. Downside: the asyncData of the page might be less readable because it's loading the data for other components.

まとめ

  • 初回の場合はSSR、再描画時はCSRなどライフサイクルが違う
  • ライフサイクルはpluginmiddlewarevalidateasyncDatafetchbeforeCreateの順で処理が実行されている

参考にさせていただいた記事

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4