What it means
While next build runs, Next.js loads each route's module to read its settings. If a file runs code as soon as it is loaded, that code runs during the build too. When it throws, the build stops and names the route. The real cause is the error printed above that line.
The usual causes
-
A variable read at the top of a file. For example
new Stripe(process.env.STRIPE_SECRET_KEY)throws when the variable is not set during the build. -
A database connection opened at import time. The build has no database to connect to.
-
A network call at the top of a file. An API called when the file loads runs during the build.
How to fix it
Move the work inside the handler, or create the client the first time it is needed.
// lib/stripe.ts
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
# After: runs on the first request
let client;
export function getStripe() {
return (client ??= new Stripe(process.env.STRIPE_SECRET_KEY));
}
Then call getStripe() inside your route handler. The same idea works for a database pool or any other client.
Why adding the secret does not help
Secrets you save on Antideploy are available when your app runs, not while the image is being built. So saving STRIPE_SECRET_KEY as a variable will not make the build see it. Variables that start with NEXT_PUBLIC_ are different: they are copied into the built files, so they must be set before the build. Never put a secret in one.