Using Prisma Client in a Next.js project in a monorepo setup
If you use Prisma Client in a Next.js application within a monorepo, you will likely run into an error such as the following:
Error: Your schema.prisma could not be found, and we detected that you are using Next.js.Find out why and learn how to fix this: https://pris.ly/d/schema-not-found-nextjs
If you are using a Prisma version earlier than 4.11.0, the error message you will recieve will look similar to the message below:
Error: ENOENT: no such file or directory, open '/prisma-next-mono-reproduction/packages/service/.next/cache/webpack/client-development/schema.prisma'
Assume you have a monorepo with the following structure:
.├── packages│ ├── db│ │ ├── index.ts│ │ ├── node_modules│ │ ├── package.json│ │ └── prisma│ │ ├── client // <-- Custom output location for the generated Prisma Client│ │ │ ├── index.js│ │ │ ├── libquery_engine-debian-openssl-1.1.x.so.node // engine to be copied│ │ │ └── schema.prisma // schema to be copied│ │ └── schema.prisma│ └── service/│ ├── pages/│ │ └── api/│ │ └── test.js│ ├── next.config.js│ └── package.json├── pnpm-workspace.yaml├── package.json└── vercel.json
The file tree above shows a monorepo contained in a
packages folder. Inside, there are two packages:
db: Contains the generated Prisma Client in a custom output location named
index.tsat the root of this package exports the instantiated Prisma Client.
service: Contains a Next.js application. The
test.jsAPI route uses the Prisma Client instance provided by the
The error mentioned above occurs as a result of a bundling problem during Next.js's bundling process. The
schema.prisma and Query Engine files are expected to be found next to the generated Prisma Client. The bundling process, however, does not copy over those files to the output location of the bundle.
For a more detailed explanation of exactly what is going wrong during the bundling process, please refer to this issue we opened in the Next.js GitHub repository.
To work around this issue, you can use a custom Webpack plugin we created that correctly copies the files Prisma Client needs to their correct location.
To use this plugin, first install the package:
You can then import the plugin into your
next.config.js file and use it in
config.plugins. For example: