Next.js Discord

Discord Forum

middleware error while using Auth.js

Answered
mihir posted this in #help-forum
Open in Discord
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 isApiRoute = nextUrl.pathname.startsWith(apiAuthPrefix)
    // const isBlogRoute = nextUrl.pathname.startsWith(blogPrefix)
    const isPublicRoute = publicRoutes.includes(nextUrl.pathname)
    const isAuthRoute = authRoutes.includes(nextUrl.pathname)

    if (isApiRoute) return null
    // if (isBlogRoute) 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
})


export const config = {
    matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
}
Answered by Cuvier’s Dwarf Caiman
Try not returning null, but just do ‘return;’
View full answer

6 Replies

c++
./middleware.ts:13:21
Type error: 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, ctx: AppRouteHandlerFnContext) => 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, ctx: AppRouteHandlerFnContext) => 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>'.
  11 | const { auth } = NextAuth(authConfig)
  12 |
> 13 | export default auth((req) => {
     |                     ^
  14 |     const { nextUrl } = req
  15 |     const isLoggedIn = !!req.auth
  16 |
Error: Command "npm run build" exited with 1
for now i'm using a bandaid as changing file to js intead of ts but if you find a soultion please let me know
Cuvier’s Dwarf Caiman
Try not returning null, but just do ‘return;’
Answer
no ai was able to figure it out
this means alot thanks bro