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初心者が最初に知るべき「DTO設計」入門【App Router対応】

0
Posted at

Next.jsでアプリ開発をしていると、次のようなコードを書いたことはありませんか?

return Response.json(user)

データベースから取得したデータを、そのままAPIレスポンスとして返す実装です。

一見問題なさそうですが、実務では この書き方はほぼNG とされています。

この記事では、初心者向けに

  • DTOとは何か?
  • なぜ必要なのか?
  • Next.js(App Router)でどう使うのか?

をやさしく解説します。


想定読者

  • Next.js を学び始めた方
  • App Router を使い始めた方
  • CRUDアプリは作れるが設計に自信がない方
  • 実務に近い構成を知りたい方

DTOとは?

DTOとは Data Transfer Object の略です。

難しく聞こえますが、シンプルに言うと:

外に出してよいデータだけを入れる箱

です。

なぜDTOが必要なのか?

例えば次のUserモデル。

type User = {
  id: string
  email: string
  password: string
  createdAt: Date
}

そのまま返すと:

return Response.json(user)

発生する問題

  • passwordが漏れる可能性
  • 内部DB構造が公開される
  • フロントがDB変更に依存する
  • セキュリティ事故の原因になる

Next.js公式ドキュメントでも警告されている

Next.js公式では、Server ComponentからClient Componentへ
不要なデータを渡すことは危険 と明確に説明されています。

公式例では次のように説明されています。

Server Componentから渡したデータはすべてクライアントに公開される

つまり:

<Profile user={userData} />

のように渡すと、
userDataの全フィールドがブラウザへ送信されます。
これはAPIレスポンスをそのまま返すのと同じ問題です。


DTOを使った正しい設計

公開用データを分離します。

export type UserResponseDto = {
  id: string
  email: string
}

DTOのイメージ

Database(Entity)
        ↓
   DTO(公開用)
        ↓
       UI

内部データと外部公開データを分離します。


Next.js公式が推奨する考え方

Next.jsでは以下が推奨されています。

  • Serverでデータ取得する
  • 機密情報をClientへ公開しない
  • 必要なデータのみ渡す

公式ドキュメント:

Sensitive information should not be exposed to the client

DTOはまさにこの思想を実装する方法です。


ディレクトリ構成例(App Router)

src/
 ├ dto/
 │   └ user.dto.ts
 ├ repositories/
 ├ services/
 └ app

DTOは「外部との境界」に配置します。


DTOの作り方(実践)

Step1 DTO定義

// dto/user.dto.ts
export type UserResponseDto = {
  id: string
  email: string
}

Step2 変換関数

export function toUserDto(user: User): UserResponseDto {
  return {
    id: user.id,
    email: user.email,
  }
}

Step3 Route Handlerで使用

export async function GET() {
  const users = await userRepository.findAll()

  return Response.json(
    users.map(toUserDto)
  )
}

Server Componentでも重要

App RouterではServer Componentが主役です。

const users = await repo.findAll()
const viewData = users.map(toUserDto)

UIへ渡す直前でDTOへ変換します。


初心者がやりがちなアンチパターン

❌ RepositoryがDTOを返す

DB責務が壊れる

❌ ServiceでDTO変換

ビジネスロジックと混在する


✅ 正解

外部へ出る直前でDTO化する

DTO導入のメリット

  • セキュリティ向上
  • DB変更に強い
  • API設計が明確になる
  • フロントとバックエンド分離
  • 実務レベル設計になる

Next.js公式でも Data Access Layer の導入 が推奨されています。
https://nextjs.org/docs/app/guides/data-security?utm_source=chatgpt.com

DTOはこのレイヤー設計の重要な要素です。


DTO設計の3原則

✅ 公開用型を作る
✅ 変換関数を書く
✅ 境界で変換する


まとめ

Next.js初心者の多くが最初に書くコード:

return Response.json(data)

しかしアプリが成長すると、

  • セキュリティ
  • 保守性
  • チーム開発

の問題に必ず直面します。

DTOはそれを防ぐための
最初の設計ステップ です。

小さなアプリからぜひ導入してみてください。


参考

Next.js Official Documentation

Data Security
https://nextjs.org/docs/app/guides/data-security

Data Fetching Patterns
https://nextjs.org/docs/app/building-your-application/data-fetching/patterns

Authentication Guide
https://nextjs.org/docs/pages/guides/authentication

参考記事

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?