Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type Mismatch Error with NextAuth Middleware Function Signature #10047

Closed
KennyMwendwaX opened this issue Feb 16, 2024 · 7 comments · May be fixed by #10050
Closed

Type Mismatch Error with NextAuth Middleware Function Signature #10047

KennyMwendwaX opened this issue Feb 16, 2024 · 7 comments · May be fixed by #10050
Labels
bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

Comments

@KennyMwendwaX
Copy link

Environment

System:
OS: Linux 6.5 Ubuntu 22.04.3 LTS 22.04.3 LTS (Jammy Jellyfish)
CPU: (4) x64 Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
Memory: 3.34 GB / 7.62 GB
Container: Yes
Shell: 5.1.16 - /bin/bash
Binaries:
Node: 20.10.0 - ~/.nvm/versions/node/v20.10.0/bin/node
npm: 10.2.3 - ~/.nvm/versions/node/v20.10.0/bin/npm
Browsers:
Brave Browser: 121.1.62.162
Chrome: 121.0.6167.160
npmPackages:
@auth/drizzle-adapter: ^0.7.0 => 0.7.0
@auth/prisma-adapter: ^1.0.13 => 1.3.3
next: ^14.1.0 => 14.1.0
next-auth: ^5.0.0-beta.11 => 5.0.0-beta.11
react: ^18.2.0 => 18.2.0

Reproduction URL

https://github.com/kenny-mwendwa/task-tracker/blob/main/src/middleware.ts

Describe the issue

The issue I'm encountering involves a type mismatch error with the function signature expected by NextAuth middleware. Specifically, when attempting to use a custom authentication middleware function, I receive the following error message:
Type Error: (shorter version)
No overload matches this call.
...
Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type 'GetServerSidePropsContext'.
...

How to reproduce

import {
  DEFAULT_ROUTE_REDIRECT,
  apiAuthPrefix,
  publicRoutes,
  authRoutes,
} from "./routes";
import { auth } from "./auth";

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);

  // Order of the checking the auth in routes matters
  if (isApiAuthRoute) return null;

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

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

  return null;
});

Expected behavior

There should be type error in the middleware, since I have used the docs example for xtending request with auth: https://authjs.dev/reference/nextjs#in-middleware

@KennyMwendwaX KennyMwendwaX added bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Feb 16, 2024
@ajstars1
Copy link
Contributor

Yes I'm also having the same issue

the exact error 👇

Screenshot 2024-02-17 at 5 31 41 AM

and In the Config file,

I'm using credentials that return null if credentials don't match

@fjobeir
Copy link

fjobeir commented Feb 17, 2024

Here is the solution guys
https://www.fjobeir.com/using-nextauthrequest-in-nextjs-middleware/

@ajstars1
Copy link
Contributor

@fjobeir Yes we have to fix it like that till its code is updated

@Vegas97
Copy link

Vegas97 commented Mar 28, 2024

Here is the solution guys https://www.fjobeir.com/using-nextauthrequest-in-nextjs-middleware/

Mannn You Saved My Day TNX !! ♥️

@anburocky3
Copy link

Still returning null has issue.

@aifirstd3v
Copy link

aifirstd3v commented Apr 29, 2024

@anburocky3 @Vegas97 @ajstars1 @fjobeir @kenny-mwendwa

Since ^5.0.0-beta.17, AppRouteHandlerFnContext has been added. so I wrote this code.
But, I'm not sure I can' return NextResponse.next() because if I use "return null", vscode complains "Type 'null' is not assignable to type 'void | Response'"

I also I'm not sure I can add additional middleware2 function because I used "return NextResponse.next() like this :

import NextAuth, { NextAuthResult, Session } from 'next-auth'
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  protectedRoutes,
  publicRoutes
} from '@/routes'
import { NextRequest, NextResponse } from 'next/server'
import authConfig from './auth.config-next'

const { auth } = NextAuth(authConfig) as NextAuthResult

type AppRouteHandlerFnContext = {
  params?: Record<string, string | string[]>
}

// not sure if the function name can be 'middleware' not auth
// https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/index.tsx
//
export const authMiddleware = auth(
  (
    req: NextRequest & { auth: Session | null },
    ctx: AppRouteHandlerFnContext
  ): Response | void  => {
    console.log('auth middleware: ', req.nextUrl)
    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 NextResponse.next()
    }

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

    if (!isLoggedIn && !isPublicRoute) {
      let callbackUrl = nextUrl.pathname
      if (nextUrl.search) {
        callbackUrl += nextUrl.search
      }

      const encodedCallbackUrl = encodeURIComponent(callbackUrl)

      return Response.redirect(new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl))
    }

    return NextResponse.next()
    // return null
  }
)

export function middleware2(req: NextRequest) {
  console.log('middleware2: ', req.nextUrl)

  const currentUser = req.cookies.get('currentUser')?.value

  if (
    protectedRoutes.includes(req.nextUrl.pathname) &&
    (!currentUser || Date.now() > JSON.parse(currentUser).expiredAt)
  ) {
    req.cookies.delete('currentUser')
    const response = NextResponse.redirect(new URL('/login', req.url))
    response.cookies.delete('currentUser')

    return response
  }

  if (authRoutes.includes(req.nextUrl.pathname) && currentUser) {
    return NextResponse.redirect(new URL('/profile', req.url))
  }
}

export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
}

export default authMiddleware

@jakobevangelista
Copy link

jakobevangelista commented Jun 18, 2024

@aifirstd3v any updates on using 2 different middlewares? I'm implementing something similar and trying to nest this auth function

const { auth } = NextAuth(authConfig);

const nextauthMiddle = auth(function middleware(req) {
  console.log("MIDDLE WARE WORK NEXT AUTH");

  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 NextResponse.next();
  }

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

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

  return NextResponse.next();
});

export default middleWare(
  ( request) => {
    return nextauthMiddle(request);
  }
);

but I can't seem to get it to works, I'm nesting it within a function and passing it the request, but it's asking for a context with the type AppRouteHandlerFnContext.

Any help appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.
Projects
None yet
7 participants