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

遵循Supabase Auth + Next.js App Router教程时服务器启动报错

问题描述

按照Supabase Auth + Next.js App Router教程开发,启动开发服务器后出现服务器错误,已确认.env.local文件中NEXT_PUBLIC_SUPABASE_URL和NEXT_PUBLIC_SUPABASE_ANON_KEY配置正确,当前middleware.ts代码如下:

import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'

import type { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
  const res = NextResponse.next()

  // Create a Supabase client configured to use cookies
  const supabase = createMiddlewareClient({ req, res })

  // Refresh session if expired - required for Server Components
  await supabase.auth.getSession()

  return res
}
排查与解决建议
  • 重启开发服务器:环境变量修改后必须重启Next.js开发服务器,否则新配置不会生效。停止当前服务后重新运行npm run dev或yarn dev。
  • 核对环境变量命名:确保.env.local中的变量名完全正确,必须为NEXT_PUBLIC_SUPABASE_URL和NEXT_PUBLIC_SUPABASE_ANON_KEY,注意大小写和前缀NEXT_PUBLIC_不能省略。
  • 匹配依赖版本:确保@supabase/auth-helpers-nextjs与next版本兼容,可执行以下命令安装最新兼容版本:
    npm install @supabase/auth-helpers-nextjs@latest next@latest
    
  • 添加中间件匹配规则:在middleware.ts末尾导出配置,避免中间件拦截静态资源引发错误:
    export const config = {
      matcher: [
        '/((?!_next/static|_next/image|favicon.ico).*)',
      ],
    }
    
  • 捕获错误日志:修改middleware.ts添加错误捕获,打印具体错误信息定位问题:
    export async function middleware(req: NextRequest) {
      const res = NextResponse.next()
    
      try {
        const supabase = createMiddlewareClient({ req, res })
        await supabase.auth.getSession()
      } catch (error) {
        console.error('Middleware error:', error)
      }
    
      return res
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:42:49