BlogNext.js

Failed to collect page data for /api/users How to fix it.

Next.js runs each route's module while it builds. Something at the top of that file threw. Move it inside the handler.

How the Agent API works
What you see
Error: Neither apiKey nor config.authenticator provided
    at ...
> Build error occurred
Error: Failed to collect page data for /api/checkout
  • What it meansCode ran at import time and threw
  • The fixMake clients and variables lazy
  • SecretsNot available while the image builds
  • Where it failsIn next build

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.

Before: runs during the build
// 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.

01Questions

Next.js build questions, answered.

Anything else? Write to us and a person answers.

support@antideploy.com
Can I give the variable a fallback instead?

Yes. A fallback lets the module load without the real value. Use it only if the code never needs the real value during the build.

Does it only fail in production?

It fails in next build. next dev does not run every route at start, so it can hide the problem.

Does this failed deploy cost anything?

No. Failed deploys never count against your plan.

Deploy something. Start with one sentence.

Paste one sentence into your coding agent, click Approve once, and get a live link. No card, no trial clock.

Start from GitHub or a folder
Prompt copied Paste it into Claude Code, Codex or Cursor and press Enter.