From f2fc73d2dca24bc288d2375ed36f4bf3fe59bc4d Mon Sep 17 00:00:00 2001 From: Michael Zetterberg Date: Thu, 28 Mar 2024 06:48:56 +0100 Subject: [PATCH] chore: update comment on middleware conditional use of auth --- middleware.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/middleware.ts b/middleware.ts index 83457883c..0b8ab87be 100644 --- a/middleware.ts +++ b/middleware.ts @@ -83,16 +83,26 @@ export async function middleware(request: NextRequest) { const isProtectedRoute = protectedRoutes.includes(nextUrl.pathname) if (isProtectedRoute) { /** - * AppRouteHandlerFnContext is the context that is passed to the handler as the - * second argument. + * AppRouteHandlerFnContext is the context that is passed to the handler as + * the second argument. This is only done for Route handlers (route.js) and + * not for middleware. * - * type AppRouteHandlerFnContext = { - * params?: Record - * } + * Auth.js uses the same pattern for both Route handlers and Middleware, + * the auth()-wrapper: * - * We don't need it so just pass an empty object + * auth((req) => { ... }) + * + * But there is a difference between middleware and route handlers, route + * handlers get passed a context which middleware do not get. Using the + * same function for both works runtime because second argument is just + * undefined for middleware and Auth.js handles this properly. But fails in + * typings as the second argument doesn't exist for middleware. + * + * https://github.com/nextauthjs/next-auth/blob/3c035ec62f2f21d7cab65504ba83fb1a9a13be01/packages/next-auth/src/lib/index.ts#L265 + * https://authjs.dev/reference/nextjs */ - return authedMiddleware(request, {}) + // @ts-expect-error: see above + return authedMiddleware(request) } else { return publiceMiddleware(request) }