Fixing "supabaseUrl is required" when next build fails (tested repro, Next 16 + supabase-js 2.109)
Description and use
Next.js 16 build fails because createClient is called at module level when env vars are missing. Moving client creation into a request‑time function fixes the build and provides a clear runtime error.
Problem
A Next.js build fails with "Error: supabaseUrl is required." when a Supabase client is instantiated at module top level and environment variables are missing during build.
Outcome
The build succeeds after moving client creation into a request‑time function, and runtime errors clearly indicate missing environment variables.
Workflow
- 1. Identify top‑level createClient calls in route files.
2. Move each call into a getSupabase() function that reads process.env at request time.
3. Add a clear error if NEXT_PUBLIC_SUPABASE_URL or NEXT_PUBLIC_SUPABASE_ANON_KEY is missing.
4. Replace direct supabase usage with getSupabase() in handlers.
5. Rebuild with
npx next build. 6. Verify runtime error handling withnpx next startand a POST request.
Evidence
If a route file does this at module scope: const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY); …then createClient runs during the build.
Create the client inside a function and call it in the handler.
All runs on 2026-10-18, no .env file, no Supabase variables set: Before: npx next build → failed with the error above, exit code 1. After: npx next build → exit code 0; output listed ƒ /api/waitlist as a dynamic route.
- Record date: 2026-10-20T03:41:16.400Z