使用Next.js调用Supabase时出现TypeError: fetch failed错误
Next.js + Supabase 出现 TypeError: fetch failed 排查方案
问题场景
在Next.js的API路由中调用Supabase查询指定表数据,表已确认存在且填充数据,但每次请求都会触发错误分支,返回TypeError: fetch failed错误。
相关代码
import type { NextApiRequest, NextApiResponse } from 'next'; import { supabase } from "../../utils/db"; // 该代码已在全应用正常使用 export default async function handler( req: NextApiRequest, res: NextApiResponse ) { let { data, error } = await supabase.from('tableName') // tableName存在且有数据 .select(` id, created_at, date, position, description, tags, apply_url, slug, job_type, approved, customer_deactivation, featured, dashboard_url, review_id, category_name, email, global_talent, hq, website, meta_description, location, visa_sponsorship, company (id, company_name, company_website, company_description, company_email, company_logo) `); if (error) { console.info("IF: ", { error }); return res.json({ message: error.message}); } }
完整错误信息
IF: { error: { message: 'TypeError: fetch failed', details: 'TypeError: fetch failed\n' + ' at Object.fetch (node:internal/deps/undici/undici:11600:11)\n' + ' at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n' + ' at async handler (webpack-internal:///(api)/./pages/api/jobs.ts:16:48)', hint: '', code: '' } }
排查解决方案
检查Supabase环境变量配置
确认.env.local里的NEXT_PUBLIC_SUPABASE_URL和NEXT_PUBLIC_SUPABASE_ANON_KEY是否完全正确,开发/生产环境的配置别搞混。如果是服务端调用,也可以试试用服务端密钥SUPABASE_SERVICE_ROLE_KEY,确保权限足够。测试网络连通性
本地或服务器环境先直接用curl访问Supabase的API地址,看能不能正常连通;同时去Supabase控制台看服务状态,有没有停机维护。替换fetch实现
Node.js内置的undici fetch可能和Supabase客户端有兼容问题,试试用node-fetch替代:- 安装依赖:
npm install node-fetch - 修改Supabase客户端配置文件(
utils/db.ts):import { createClient } from '@supabase/supabase-js'; import fetch from 'node-fetch'; const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!; const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!; export const supabase = createClient(supabaseUrl, supabaseAnonKey, { global: { fetch: fetch as any, }, });
- 安装依赖:
简化查询语句排查语法问题
先去掉关联表company的查询,简化成只查几个基础字段,看能不能正常返回数据。如果可以,再逐步加回字段和关联查询,定位具体语法错误。查看Supabase日志
登录Supabase控制台,进入对应项目的API日志页面,里面会有更详细的错误细节,比如权限不足、SQL语法错误等,能快速定位问题。
内容的提问来源于stack exchange,提问作者26ph19
相关产品推荐
相关产品推荐

