Engineering from Scratch

エンジニア目指してます

getServerSideProps

Next.js は getServerSideProps によって取得したデータを使って page の pre-render を行う。

import { InferGetServerSidePropsType } from "next";

export const getServerSideProps = async (context) => {
  const res = await fetch("https://api.github.com/users/octokit");
  const data = await res.json();
  console.log(data); ← serverで実行される
  return { props: { data } };
};

const HomePage = ({
  data,
}: InferGetServerSidePropsType<typeof getServerSideProps>) => {
  console.log(data); ← ブラウザで実行される

  return <h1>Hello World</h1>;
};

export default HomePage;

getServerSideProps は以下のいずれかの値を返す必要がある。

  • props
    • {props: Object}の形で渡す必要がある
  • notFound
    • {notFound: true}を渡すと,page は 404 を返す
  • redirect
    • {redirect: {destination: string, permanent: boolean}}
    • redirect処理が走る
参考

nextjs.org