MCPcopy
hub / github.com/nextauthjs/next-auth / handleMiddleware

Function handleMiddleware

src/next/middleware.ts:56–96  ·  view source on GitHub ↗
(
  req: NextRequest,
  options: NextAuthMiddlewareOptions | undefined,
  onSuccess?: (token: JWT | null) => Promise<any>
)

Source from the content-addressed store, hash-verified

54}
55
56async function handleMiddleware(
57 req: NextRequest,
58 options: NextAuthMiddlewareOptions | undefined,
59 onSuccess?: (token: JWT | null) => Promise<any>
60) {
61 const signInPage = options?.pages?.signIn ?? "/api/auth/signin"
62 const errorPage = options?.pages?.error ?? "/api/auth/error"
63 const basePath = parseUrl(process.env.NEXTAUTH_URL).path
64 // Avoid infinite redirect loop
65 if (
66 req.nextUrl.pathname.startsWith(basePath) ||
67 [signInPage, errorPage].includes(req.nextUrl.pathname)
68 ) {
69 return
70 }
71
72 if (!process.env.NEXTAUTH_SECRET) {
73 console.error(
74 `[next-auth][error][NO_SECRET]`,
75 `\nhttps://next-auth.js.org/errors#no_secret`
76 )
77
78 const errorUrl = new URL(errorPage, req.nextUrl.origin)
79 errorUrl.searchParams.append("error", "Configuration")
80
81 return NextResponse.redirect(errorUrl)
82 }
83
84 const token = await getToken({ req: req as any })
85
86 const isAuthorized =
87 (await options?.callbacks?.authorized?.({ req, token })) ?? !!token
88
89 // the user is authorized, let the middleware handle the rest
90 if (isAuthorized) return await onSuccess?.(token)
91
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)
96}
97
98export type WithAuthArgs =
99 | [NextRequest]

Callers 1

withAuthFunction · 0.85

Calls 2

getTokenFunction · 0.90
parseUrlFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…