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

fix(middleware): use includes() for NextAuth pages #5104

Merged
merged 3 commits into from Sep 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/next-auth/src/next/middleware.ts
Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions 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()
})