I'm encountering a TypeScript error while working with NextAuth middleware in my Next.js application. The error message I'm receiving is:
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 parameter of 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>'.
I have a middleware function that is supposed to handle authentication logic using NextAuth, but it seems that the function signature is not matching what NextAuth expects.
Here's my middleware function:
//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 null;
}
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
}
return null;
}
if (!isLoggedIn && !isPublicRoute) {
return Response.redirect(new URL("/auth/login", nextUrl));
}
return null;
})
// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}
I'm unsure how to correctly adjust my middleware function to match the expected parameter types of getServerSideProps. Any guidance on resolving this issue would be greatly appreciated.
You can just simply replace all
return null;withreturn;