Skip to content

Commit f7fc562

Browse files
fix(middleware): handle no argument case (#3799)
* fix(middleware): handle no argument case * use absolute URLs * use origin instead of host
1 parent f3be5e8 commit f7fc562

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/next/middleware.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,10 @@ async function handleMiddleware(
7575
`\nhttps://next-auth.js.org/errors#no_secret`
7676
)
7777

78-
return {
79-
redirect: NextResponse.redirect(`${errorPage}?error=Configuration`),
80-
}
78+
const errorUrl = new URL(errorPage, req.nextUrl.origin)
79+
errorUrl.searchParams.append("error", "Configuration")
80+
81+
return NextResponse.redirect(errorUrl)
8182
}
8283

8384
const token = await getToken({ req: req as any })
@@ -88,10 +89,10 @@ async function handleMiddleware(
8889
// the user is authorized, let the middleware handle the rest
8990
if (isAuthorized) return await onSuccess?.(token)
9091

91-
// the user is not logged in, re-direct to the sign-in page
92-
return NextResponse.redirect(
93-
`${signInPage}?${new URLSearchParams({ callbackUrl: req.url })}`
94-
)
92+
// the user is not logged in, redirect to the sign-in page
93+
const signInUrl = new URL(signInPage, req.nextUrl.origin)
94+
signInUrl.searchParams.append("callbackUrl", req.url)
95+
return NextResponse.redirect(signInUrl)
9596
}
9697

9798
export type WithAuthArgs =
@@ -101,6 +102,7 @@ export type WithAuthArgs =
101102
| [NextMiddleware]
102103
| [NextMiddleware, NextAuthMiddlewareOptions]
103104
| [NextAuthMiddlewareOptions]
105+
| []
104106

105107
/**
106108
* Middleware that checks if the user is authenticated/authorized.
@@ -118,7 +120,7 @@ export type WithAuthArgs =
118120
* [Documentation](https://next-auth.js.org/getting-started/middleware)
119121
*/
120122
export function withAuth(...args: WithAuthArgs) {
121-
if (args[0] instanceof NextRequest) {
123+
if (!args.length || args[0] instanceof NextRequest) {
122124
// @ts-expect-error
123125
return handleMiddleware(...args)
124126
}

0 commit comments

Comments
 (0)