-
I am trying to protect a few pages with next-auth. I also want to redirect not HTTP requests to HTTPS for all requests. Here is my middleware code. How do I make sure that the redirect works for all paths but the next-auth/middleware is applied only to the configured paths in
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I invite you the discussion I started on next-auth middleware #4791 As for how to handle redirects and authorization you need to make the middleware run for all pages. (remove matcher Config variable) Then you can call withAuth function inside middleware. import { NextResponse } from 'next/server';
import { withAuth } from "next-auth/middleware"
export function middleware(req, ev) {
//Always will Run
return withAuth(
function onSuccess(req, ev) { //function here can run custom logic and return next response.
console.log(req, ev)
return NextResponse.next();
},
{
pages: {
signIn: "/unauthorized" //-> Prevents Login Redirect loop for unauthorized.
},
callbacks: {
authorized: ({ req, token }) => req.nextUrl.pathname !== "/admin" || token?.userRole === "admin"
}
}
)
}
|
Beta Was this translation helpful? Give feedback.
-
Here is the complete solution that worked for me.
|
Beta Was this translation helpful? Give feedback.
Here is the complete solution that worked for me.