docker build: env variables in api files
Unanswered
American Wirehair posted this in #help-forum
American WirehairOP
Hey guys! I am just trying to build my next.js app to a docker image. sadly, its failing cause my API routes needs env variables (e.g. redis connection) which I dont have in the docker image: is there a way to skip that? seems like its due to the static page generation
6 Replies
American black bear
Just had this issue but with connection to the db. The solution is to never need any databases or external connections during build time
You should be connecting to your database in a try/catch block in order to prevent crashes during docker builds
Asian black bear
That is a bandaid. The correct way is to mark the route as dynamic to not have it be statically prerendered.
American black bear
@Asian black bear I am interested in this. My dev tools were saying that the route was dynamic, however it still ended up throwing an error when I was building the image, until I put fetching logic and client creation in try/catch block. Is there some docs regarding how next.js build works?
Asian black bear
Unless a page or route uses dynamic APIs such as
cookies
it is attempting to be static by default. In case you use third party libs to fetch or query data Next cannot possibly know this is dynamic which is why you need to resort to the dynamic
route segment config option.There is an example of that over here: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#fetching-data-on-the-server-with-the-fetch-api