Fixing "supabaseUrl is required" when next build fails (tested repro, Next 16 + supabase-js 2.109)
说明与用途
Next.js 16 构建失败是因为在模块级别调用 createClient,导致环境变量缺失。将客户端创建移动到请求时的函数中可解决构建错误,并在运行时提供清晰的错误信息。
问题
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.
结果
The build succeeds after moving client creation into a request‑time function, and runtime errors clearly indicate missing environment variables.
工作流
- 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.
证据
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.
- 记录日期: 2026-10-20T03:41:16.400Z