2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Next.js 9.3で追加されたgetStaticPropsでSSRからSSGにする

2
Posted at

はじめに

先日、Next.js9.3がリリースされました。

待望のSSGサポートがされ、コミュニティがだいぶ賑わっていましたね。
(個人的にはSassのサポートがかなり嬉しいです)

SSGを使いたいときに、GatsbyではなくNext.jsが選択されることも増えてくるのではないでしょうか?
私は、プライベートでGatsbyも触っていたのですが、業務ではNext.jsを使っており、GraphQLの学習コストも相まってNext.jsを選択する機会が増えていきそうなので嬉しいです。

今回は、SSRで使っていたブログを、今回追加された、getStaticPropsというSSG用のAPIを使ってSSGにしたので、簡単にですがビフォーアフターを載せておきます。

実装

ビフォー(SSR)

Home.getInitialProps = async () => {
  const key = {
    headers: { 'X-API-KEY': process.env.api_key }
  }
  const res = await axios.get('https://self-site.microcms.io/api/v1/skills', key)
  const skills = await res.data

  return { skills }
}
Page                                                           Size     First Load
┌ λ /                                                          17 kB       75.4 kB
└   /_app                                                      289 B       57.2 kB

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)

アフター(SSG)

export const getStaticProps: GetStaticProps = async () => {
  const key = {
    headers: { 'X-API-KEY': process.env.api_key }
  }
  const res = await axios.get('https://self-site.microcms.io/api/v1/skills', key)
  const skills = await res.data

  return { props: { skills } }
}
Page                                                           Size     First Load
┌ ● /                                                          11.8 kB     69.8 kB
└   /_app                                                      287 B       56.8 kB

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)

ビフォー(SSR)では元々あった、getInitialPropsを使用しています。
今は、getStaticPropsgetServerSidePropsに別れ、これらを使うことが推奨されています。
少しの変更で切り替えれるので、簡単にできました。

参考

公式 getInitialProps
公式 Data fetching

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?