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

NextAuth中间件TypeScript报错:No overload matches this call 求助

NextAuth中间件TypeScript类型错误修复方案

错误详情

触发的TypeScript错误如下:

No overload matches this call. Overload 1 of 4, '(args_0: GetServerSidePropsContext): Promise<Session | null>', gave the following error. Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type 'GetServerSidePropsContext'. Overload 2 of 4, '(args_0: (req: NextAuthRequest) => void | Response | Promise<void | Response>): AppRouteHandlerFn', gave the following error. Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to type '(req: NextAuthRequest) => void | Response | Promise<void | Response>'. Type 'Response | null' is not assignable to type 'void | Response | Promise<void | Response>'. Type 'null' is not assignable to type 'void | Response | Promise<void | Response>'.

问题原因

NextAuth中间件要求回调函数的返回值类型为void | Response | Promise<void | Response>,但当前代码中返回了null,不符合类型规范。

修复后的代码

将所有返回null的语句替换为返回undefined(或直接省略return,函数默认返回undefined):

//middleware.ts
import NextAuth from "next-auth";

import authConfig from "@/auth.config";
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes,
} from "@/routes";

const { auth } = NextAuth(authConfig);

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;

  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);

  if (isApiAuthRoute) {
    return undefined;
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
    }
    return undefined;
  }

  if (!isLoggedIn && !isPublicRoute) {
    return Response.redirect(new URL("/auth/login", nextUrl));
  }
  return undefined;
})

// Optionally, don't invoke Middleware on some paths
export const config = {
  matcher: ['/((?!.+\.[\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}

说明

当不需要对路由进行拦截或重定向时,返回undefined(或省略return语句)即可满足NextAuth中间件的类型要求,它表示允许请求继续正常处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:32:16