LoginSignup
0

More than 1 year has passed since last update.

nextjs SSGとSSRのdynamicPage 実装 動きの確認

Last updated at Posted at 2023-01-18

概要

next.js のSSGとSSRのdynamicPageの実装方法を確認します。

開発環境

OS:windows10
IDE:VScode

├── @types/node@18.11.15
├── @types/react-dom@18.0.9
├── @types/react@18.0.26
├── axios@1.2.1
├── eslint-config-next@13.0.6
├── eslint@8.29.0
├── next-auth@4.18.7
├── next@13.0.6
├── react-bootstrap@2.7.0
├── react-dom@18.2.0
├── react@18.2.0
├── styled-components@5.3.6
├── styled-jsx@5.1.1
└── typescript@4.9.4

実装

SSG -Static Site Generation

実装方法のポイントは以下の2点です。
1.ファイル名を[]で囲む
2.コード上ではgetStaticPaths()を追加する

ソースコード

products/[pid].tsx
import path from 'path';
import fs from 'fs/promises';

import { Fragment } from 'react';

function ProductDetailPage(props : any) {
  const { loadedProduct } = props;

  if (!loadedProduct) {
    return <p>Loading...</p>;
  }

  return (
    <Fragment>
      <h1>{loadedProduct.title}</h1>
      <p>{loadedProduct.description}</p>
    </Fragment>
  );
}

async function getData() {
  const filePath = path.join(process.cwd(), 'data', 'dummy-backend.json');
  const jsonData = await fs.readFile(filePath);
  const data = JSON.parse(jsonData as any);

  return data;
}

export async function getStaticProps(context :any) {
  const { params } = context;

  console.log(' SSG getStaticProps()')
  const productId = params.pid;

  const data = await getData();

  const product = data.products.find((product: { id: any; }) => product.id === productId);

  if (!product) {
    return { notFound: true };
  }

  return {
    props: {
      loadedProduct: product,
    },
  };
}

export async function getStaticPaths() {
  console.log(' SSG getStaticPaths()')
  const data = await getData();

  const ids = data.products.map((product:any) => product.id);
  const pathsWithParams = ids.map((id : any) => ({ params: { pid: id } }));

  return {
    paths: pathsWithParams,
    fallback: true,
  };
}

export default ProductDetailPage;

動きの確認

ビルドコマンドを実行する

npm run build

下はビルド結果の画像です。ビルド時にデータを取得してdynamicPageが作成されていることを確認できます。
image.png

サーバーを開いて動きを確認

npm start

以下gifアニメはproductのid(p1,p2,p3)を入力してページを確認している様子です。データ以外の値を入力すると404エラーになります。
生成されたページを開く→getStaticProps getStaticPathとも実行されない
生成されてないページを開こうとする→getStaticPropは実行され getStaticPathは実行されない
SSG_dynamicRoute.gif

SSR-Sever Side Rendering

実装するためのポイント
ファイル名を[]で囲む。

ソースコード

user/[uid].tsx
import { useAccordionButton } from "react-bootstrap";

function UserIdPage(props:any){
	
	return <h1>{props.id}</h1>
}

export default UserIdPage;

export async function getServerSideProps(context: any) {
	console.log("SSR DynamicPage")
	const { params, req, res } = context;
	const userId :string = params.uid;
	return {
	  props: {
		id:'userid-' + userId, 
	  },
	};
}

動きを確認

以下コマンドを実行してビルドする。

npm run build

ビルド結果 SSRなのでビルド時にページは生成されません。
image.png

サーバーを開いて動きを確認

npm start

以下gifアニメはSSRのdynamicRoutingの動きを確認しているときの様子です。
適当な文字列を入力しています。
毎回getServerSidePropsが実行されています。

SSR_dynamicRoute.gif

SSGとSSRの使い分け

SSG → 全てのユーザーが共通で使うページ、
SSR → ユーザー個別のページ

例えばB2CのECショップを作る場合
SSG→商品閲覧機能 ログインページ
SSR→ユーザーページ 買い物履歴

参考

Section 5 Page Pre-Rendering & Data Fetching
99-101 109-110

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
0