MeWrite Docs

PrismaClientInitializationError: Unable to require prisma/client

Prisma Clientの初期化に失敗した場合のエラー

概要

Prisma Clientの初期化時に発生するエラーです。クライアントが生成されていない、またはバイナリが見つからない場合に発生します。

エラーメッセージ

PrismaClientInitializationError: Unable to require(`/app/node_modules/.prisma/client/index.js`).
PrismaClientInitializationError: Prisma Client has not been generated yet. Run `prisma generate` and try importing it again.
Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.

原因

1. Prisma Clientが生成されていない

2. node_modulesの不整合

3. ビルド時にgenerateが実行されていない

4. Query Engineバイナリが見つからない

解決策

1. Prisma Clientを再生成

1
npx prisma generate

2. node_modulesを再インストール

1
2
3
4
rm -rf node_modules
rm package-lock.json  # または yarn.lock
npm install
npx prisma generate

3. postinstallスクリプトを追加

1
2
3
4
5
6
// package.json
{
  "scripts": {
    "postinstall": "prisma generate"
  }
}

4. ビルドスクリプトにgenerateを追加

1
2
3
4
5
6
7
// package.json
{
  "scripts": {
    "build": "prisma generate && tsc",
    "vercel-build": "prisma generate && next build"
  }
}

5. Docker環境での対処

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Dockerfile
FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
COPY prisma ./prisma/

RUN npm install
RUN npx prisma generate

COPY . .

RUN npm run build

6. Vercel/Netlifyでの対処

1
2
3
4
5
6
// package.json
{
  "scripts": {
    "postinstall": "prisma generate"
  }
}

またはvercel.json:

1
2
3
{
  "buildCommand": "prisma generate && npm run build"
}

7. モノレポでの対処

1
2
3
4
5
6
// apps/web/package.json
{
  "scripts": {
    "postinstall": "cd ../../packages/database && prisma generate"
  }
}

8. ESM/CommonJSの問題

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ESM環境での正しいインポート
import { PrismaClient } from '@prisma/client'

// シングルトンパターン(推奨)
const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined
}

export const prisma = globalForPrisma.prisma ?? new PrismaClient()

if (process.env.NODE_ENV !== 'production') {
  globalForPrisma.prisma = prisma
}

バイナリ関連のエラー

Query Engineが見つからない

1
2
3
4
5
6
# binaryTargetsを明示的に指定
# schema.prisma
generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
}

Alpine Linuxの場合

1
2
# Alpine用のOpenSSLをインストール
RUN apk add --no-cache openssl

デバッグ方法

1
2
3
4
5
6
# Prismaの情報を表示
npx prisma --version
npx prisma validate

# 生成されたクライアントを確認
ls -la node_modules/.prisma/client/

関連エラー

関連エラー

Prisma の他のエラー

最終更新: 2025-12-18