Next.js 14 'next build' fails 'ENOENT: no such file or directory, open /run/secrets/...' / 'Failed to collect page data for /api/...': secret read at module scope in a route handler
Next.js 14.2.15 App Router dashboard (a backend proxy for the Nessie v2 API, since the API sends no CORS headers) built in a multi-stage node:22-alpine Containerfile. The API key is mounted at runtime as a file (/run/secrets/nessie_key), and each route.ts did this at the top of the module:
const API_KEY = readFileSync('/run/secrets/nessie_key', 'utf8').trim();
RUN npm run build failed after "Compiled successfully" and "Collecting page data ...":
Error: ENOENT: no such file or directory, open '/run/secrets/nessie_key' at readFileSync (node:fs:440:20) at ... (/app/.next/server/app/api/merchants/[id]/route.js:1:545) > Build error occurred Error: Failed to collect page data for /api/merchants/[id]
Cause: during "Collecting page data" next build imports every route module to read its config exports, so top-level code runs at build time, where the runtime secret does not exist.
Fix: read the secret lazily inside the handler path, e.g. src/lib/api.ts:
let cached: string | null = null;
export function getApiKey() {
if (!cached) cached = readFileSync('/run/secrets/nessie_key', 'utf8').trim();
return cached;
}
export const getAuthHeaders = () => ({ Authorization: Bearer ${getApiKey()} });
and call getAuthHeaders() inside GET/POST. The build then passes.
Second gotcha after that fix: the build still printed "Error fetching customers: Error: ENOENT ..." during "Generating static pages (2/10)". In Next 14 a GET route handler that does not read the request (no request.url, headers() or cookies()) is static by default, so next build runs it to prerender the response. Here it failed, so the route stayed dynamic and the build only logged noise. But if the key had been available at build time (e.g. a build arg or env var), the Nessie response from build time would have been frozen into the image. Add export const dynamic = 'force-dynamic' (or read request.nextUrl.searchParams) to proxy routes that must hit the API on every request. Verify with the build output's route table (λ dynamic vs ○ static) or by checking there is no .next/server/app/api/<route>.body file in the image.