You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14动态路由从Supabase获取单帖返回null问题排查

Next.js + Supabase 单帖获取返回null问题

问题背景

开发Next.js应用,从Supabase数据库获取名为bounties的帖子,获取全部帖子功能正常,但通过ID动态获取单篇帖子时页面返回null。

获取全部帖子的代码(app/notes/page.tsx)

import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { cookies  } from "next/headers";
import { createSupabaseAppServerClient } from "@/utils/supabase/supabaseAppRouterClient";

import {createBrowserClient, createServerClient} from "@supabase/ssr";

export default async function Notes() {

    // const supabase1 = createSupabaseAppServerClient(true);
    
    const supabase = createServerComponentClient<any, "public", any>( { cookies},
         {supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL,
         supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,});
    const { data } = await supabase.from("bounties").select();
    return( 
        <pre>{JSON.stringify(data, null, 2)}</pre>
    );
}

动态获取单帖的代码(app/pages/notes/[...id])

import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";


export default async function Page(
    {params : {id}} : {params: {id: string}}
    ) {
    const supabase = createServerComponentClient<any, "public", any>( { cookies},
        {supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL,
        supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,});
    
    const { data} = await supabase.from('bounties').select().eq('id', 'bounty_id').single();
    return(
        <pre>{JSON.stringify(data, null, 2)}</pre>
    );
}

问题原因与修复

返回null的核心问题有两个:

  1. 查询条件错误:代码中eq('id', 'bounty_id')是把字符串'bounty_id'当成查询值,而非使用URL传递的动态id参数。
  2. 路由路径错误:App Router的动态路由应放在app/notes/[id]/page.tsx,当前app/pages/notes/[...id]是Pages Router的写法,且[...id]作为catch-all路由,params.id会是数组类型而非单个字符串。

具体修复步骤:

  1. 调整路由结构
    将动态页面文件移动到app/notes/[id]/page.tsx,符合App Router的路由规则。若需保留catch-all路由,需将参数处理为id[0](取数组第一个元素)。

  2. 修正查询逻辑
    将查询条件改为使用URL传递的id参数,同时添加错误排查:

    const { data, error } = await supabase.from('bounties').select().eq('id', id).single();
    
    if (error) {
        return <pre>查询错误:{JSON.stringify(error, null, 2)}</pre>;
    }
    
  3. 匹配字段类型
    如果数据库中id是数字类型,需将参数转为数字:eq('id', parseInt(id)),避免类型不匹配导致无结果。

内容的提问来源于stack exchange,提问作者kaks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:32:25