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

Next.jsのサーバーサイドレンダリング(SSR)とクライアントサイドレンダリング(CSR)を爆速で試す

0
Last updated at Posted at 2026-02-16

やりたいこと

Next.jsのサーバーサイドレンダリングとクライアントサイドレンダリングを試す

環境構築

Dokerfileを配置

FROM node:20
WORKDIR /app
COPY . .
EXPOSE 8080

docker-compose.ymlを配置

version: "3"
services:
  nextjs_study:
    build:
      context: .
      dockerfile: ./Dockerfile
    container_name: nextjs_study
    tty: true
    command: /bin/bash
    user: root

コンテナ起動

docker compose up --build  -d

VSCode⇒DevContainersでコンテナアクセス(ない場合はインストール※)で開く
image.png


image.png

Next.jsインストール

>npx create-next-app@latest sample --typescript

yes+全てエンター
image.png

サーバーサイドレンダリングソースを置く

>cd /app/sample/app
>mkdir -p server/[id]
>cd server/[id]

/app/sample/app/server/[id]に以下を配置

page.tsx

'use server'

async function requestApi() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts')
  return res.json()
}

export default async function SampleServer({ params }: { params: Promise<{ id: string }> }) {
  const res = await requestApi()
  const { id } = await params;

  return (
    <div>userId:{res[0].userId} paramId: {id}</div>
  )
}

クライアントサイドレンダリングソースを置く

>cd /app/sample/app
>mkdir -p client/[id]
>cd client/[id]

/app/sample/app/client/[id]に以下を配置

page.tsx

'use client';

import { useParams  } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function SampleClient() {
  const [data, setData] = useState<string>();
  useEffect(() => {
      (
        async() => {
        const res = fetch('https://jsonplaceholder.typicode.com/posts');
        const d = await (await res).json();
        setData(d[0].userId);
        }
      )();
  }, [])
  const params = useParams(); const id = params.id;
  return <h1>userId: {data} paramId: {id}</h1>;
}

アプリ起動

>cd /app/sample
>npm run dev ※package.jsonから起動するとSSRをストップできる(どちらかで起動)

※ package.jsonから起動すると場合
image.png

動確

SSR

http://localhost:3000/server/1

image.png

package.jsonからの起動はサーバー側でストップすることができる
image.png

CSR

http://localhost:3000/client/1

image.png

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