How to handle redirecting to error page from middleware?
Answered
Bonga shad posted this in #help-forum
Bonga shadOP
I have a middleware where I want to check if the user has certain roles on the session object. I want to do some mapping to see if the page is whitelisted and then if not redirect to the error page saying this page is not allowed. I am using next 14 with app router. How can I achieve that ? I've tried NextReponse.error() and redirecting to /error page but I just get 404 page not found.
Answered by Asian black bear
You then just redirect to
/error or whatever is applicable here.6 Replies
Asian black bear
return NextResponse.redirect(new URL('/login', request.url))@Asian black bear ts
return NextResponse.redirect(new URL('/login', request.url))
Bonga shadOP
thanks for the reply. I don't want to redirect them to the login page or log them out. I am referring to logged in users who have access to other pages.
Asian black bear
You then just redirect to
/error or whatever is applicable here.Answer
Asian black bear
Just pick a suitable path that you want to send your user to.
Bonga shadOP
thanks a lot, that makes sense. btw would I take advantage of one of the default Error UI error.tsx pages inside of the page folder or I would actually define my own error/page.tsx?
Asian black bear
You'd redirect to a custom page. The
error.tsx pages are for unhandled server-side errors.