[Fixed] Database connection on nextjs build time

February 15, 2025

2 mins read

When building a nextjs app, it will connect to your database as part of static generation. You can fix this by either using any of the three: Dynamic APIs, Route Segment, and experimental build argument next build --experimental-build-mode compile

I was editing the Dockerfile of this portfolio website while making sure that it'll output the smallest possible image for deployment. However, I was surprised to see that Prisma is trying to connect to my database, and actually causes my whole build stop 🤔. The only layer that involves Prisma is for generating the Prisma client which doesn't require any connection. A weird one that took me hours to look for the cause.

🐛 Root cause

Nextjs is good for all those statically generated sites, and it wants to cache or generate everything as early as possible thus wanting to statically generate even the routes that involves Prisma. Well, in our case databases can't be accessed on build time, so this renders the whole Nextjs + Prisma thing unusable, and obviously we wouldn't want our routes to be presumed as static.

You may want to read what's dynamic and static rendering here. 😉

💫 Solution

Now we have 3 solutions:

  1. Use any of the Dynamic APIs, which tells Nextjs that we want this page or route to be dynamically rendered.
  2. Add Route Segment, dynamic, to pages and routes we want to explicitly state as dynamic or static.
  3. Experimental build argument next build --experimental-build-mode compile which makes all routes dynamically rendered without opting in to ISR cache.

All these can make our routes rendered dynamically.

🗒️ References

Reddit

Github

© 2025 Alec Blance

Bacolod, PH