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

Next.js/TypeScript中间件调用报错:无匹配重载项

NextAuth中间件TypeScript类型报错解决方案

报错信息

没有匹配的重载调用。
重载1(共4个):'(args_0: GetServerSidePropsContext): Promise<Session | null>',给出以下错误:
类型为'(req: NextAuthRequest) => Response | null'的参数无法赋值给类型为'GetServerSidePropsContext'的参数。
重载2(共4个):'(args_0: (req: NextAuthRequest) => void | Response | Promise<void | Response>): AppRouteHandlerFn',给出以下错误:
类型为'(req: NextAuthRequest) => Response | null'的参数无法赋值给类型为'(req: NextAuthRequest) => void | Response | Promise<void | Response>'的参数。
类型'Response | null'无法赋值给类型'void | Response | Promise<void | Response>'。
类型'null'无法赋值给类型'void | Response | Promise<void | Response>'。ts(2769)
(parameter) req: NextAuthRequest

问题原因

NextAuth的auth中间件回调函数不允许返回null,合法的返回值只能是:

  • void/undefined(表示继续执行后续逻辑)
  • Response对象(用于重定向等操作)
  • 上述类型的Promise

你代码中多处返回null,违反了TypeScript的类型约束,导致报错。

修复后的代码

import authConfig from "@/auth.config";
import NextAuth from "next-auth";
import {
  apiAuthPrefix,
  DEFAULT_LOGIN_REDIRECT,
  authRoutes,
  publicRoutes,
} from "@/routes";
export const { auth } = NextAuth(authConfig);

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;
  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);
  const isPublicRoute = publicRoutes.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)(.*)"],
};

关键改动说明

将所有return null替换为return undefined,或者直接省略return语句(函数默认返回undefined),这样就能符合NextAuth中间件的类型要求,解决类型报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:47:20