💭

【Next.js】"PrismaClientInitializationError"について

に公開

🏴󠁧󠁢󠁳󠁣󠁴󠁿目的

解決が難しく、参考になる日本語文献を見つける事が出来なかったため、
エラー発生状況と対処策を残します。

❗前提

  • "Next.js": "15.1.0",
  • "react": "18.3.1",
  • "prisma": "6.7.0"
  • 使用DB: Neon
  • ホスティング先: Vercel

😕エラー内容

PrismaClientのfindMany()やfindUnique()メソッドなどDBからfetchする関数が、
メッセージ"Error [PrismaClientInitializationError]"と共に失敗する。

💻処理内容

エラーが起きた処理は、以下のコードのような、DB検索を行うサーバーアクションです。
実際の実装ではクライアントコンポーネントからこのサーバーアクションを呼び出して使います。

※一部抜粋

app/actions/adminActions.ts
"use server";
import prisma from "@/lib/prisma";

export async function getProductsByBrands(brands: string[]) {
    const products = await prisma.products.findMany({
        where: { brand: { in: brands }},
        select: { id: true,
                  product_name: true,
                  stock: true,
                  brand: true },
        orderBy: { product_name: 'asc' },
    });
    return products;
}

export async function findUser(userId: number) {
    const user = await prisma.users.findUnique({
        where: { id: userId },
        select: {
            id: true,
            full_name: true,
            email: true,
            postal_code: true,
            address: true,
            phone_number: true,
        },
    })
    return user;
}

🗨️詳細なエラーメッセージ

Error searching product sales: Error [PrismaClientInitializationError]:
Invalid prisma.products.findMany() invocation:

Prisma Client could not locate the Query Engine for runtime "rhel-openssl-3.0.x".

We detected that you are using Next.js, learn how to fix this: https://pris.ly/d/engine-not-found-nextjs.

This is likely caused by a bundler that has not copied "libquery_engine-rhel-openssl-3.0.x.so.node" next to the resulting bundle.
Ensure that "libquery_engine-rhel-openssl-3.0.x.so.node" has been copied next to the bundle or in "lib/generated/prisma".

We would appreciate if you could take the time to share some information with us.
Please help us by answering a few questions: https://pris.ly/engine-not-found-bundler-investigation

🛠️対処策

以下のstackoverflowのディスカッションを参考に、対処を実施。
https://stackoverflow.com/questions/79597648/prisma-client-could-not-locate-the-query-engine-for-runtime-rhel-openssl-3-0-x

  • schema.prismaに"binaryTargets"の指定を追加
    ※一部抜粋
schema.prisma
generator client {
  provider      = "prisma-client-js"
  output        = "../lib/generated/prisma"
  binaryTargets = ["native", "rhel-openssl-3.0.x"]
}
  • npmパッケージ"prisma/nextjs-monorepo-workaround-plugin"をインストールのうえ、
    next.config.mjsファイルにimport行とwebpackの拡張を定義して返す関数を追加
npm i @prisma/nextjs-monorepo-workaround-plugin
next.config.mjs
import { PrismaPlugin} from "@prisma/nextjs-monorepo-workaround-plugin";

/** @type {import('next').NextConfig} */

const nextConfig = {
    experimental: {
        webpackBuildWorker: true,
        parallelServerBuildTraces: true,
        parallelServerCompiles: true,
    },
    webpack: (config, { isServer }) => {
        if (isServer) {
            config.plugins = [...config.plugins, new PrismaPlugin()];
        }
        return config;
    }
}

export default nextConfig;

設定の意味

  • binaryTargetsの追加
    ・"native"
     prisma generate実行時に現在のOS向けのクエリエンジンのバイナリファイルを生成する。
    ・"rhel-openssl-3.0.x"
     Vercelの実行環境向けのクエリエンジンのバイナリファイルを生成する。

  • "webpack"ブロックの追加
    サーバー用のビルド時に既存のプラグインリストにPrismaPluginのインスタンスを含めて返す。

Discussion