diff --git a/packages/next-auth/src/next/middleware.ts b/packages/next-auth/src/next/middleware.ts index a9efb3ec7e..4837ccb39d 100644 --- a/packages/next-auth/src/next/middleware.ts +++ b/packages/next-auth/src/next/middleware.ts @@ -106,12 +106,13 @@ async function handleMiddleware( const signInPage = options?.pages?.signIn ?? "/api/auth/signin" const errorPage = options?.pages?.error ?? "/api/auth/error" const basePath = parseUrl(process.env.NEXTAUTH_URL).path - const publicPaths = [signInPage, errorPage, "/_next", "/favicon.ico"] + const publicPaths = ["/_next", "/favicon.ico"] // Avoid infinite redirects/invalid response // on paths that never require authentication if ( pathname.startsWith(basePath) || + [signInPage, errorPage].includes(pathname) || publicPaths.some((p) => pathname.startsWith(p)) ) { return diff --git a/packages/next-auth/tests/middleware.test.ts b/packages/next-auth/tests/middleware.test.ts new file mode 100644 index 0000000000..e98525f10e --- /dev/null +++ b/packages/next-auth/tests/middleware.test.ts @@ -0,0 +1,40 @@ +import { NextMiddleware } from "next/server" +import { NextAuthMiddlewareOptions, withAuth } from "../next/middleware" + +it("should not match pages as public paths", async () => { + const options: NextAuthMiddlewareOptions = { + pages: { + signIn: "/", + error: "/" + }, + secret: "secret" + } + + const nextUrl: any = { + pathname: "/protected/pathA", + search: "", + origin: "http://127.0.0.1" + } + const req: any = { nextUrl, headers: { authorization: "" } } + + const handleMiddleware = withAuth(options) as NextMiddleware + const res = await handleMiddleware(req, null) + expect(res).toBeDefined() + expect(res.status).toBe(307) +}) + +it("should not redirect on public paths", async () => { + const options: NextAuthMiddlewareOptions = { + secret: "secret" + } + const nextUrl: any = { + pathname: "/_next/foo", + search: "", + origin: "http://127.0.0.1" + } + const req: any = { nextUrl, headers: { authorization: "" } } + + const handleMiddleware = withAuth(options) as NextMiddleware + const res = await handleMiddleware(req, null) + expect(res).toBeUndefined() +})