Next.js Discord

Discord Forum

Redirect in Server Actions

Unanswered
Standard Chinchilla posted this in #help-forum
Open in Discord
Standard ChinchillaOP
Hi, I have a question/problem. I'm validating in a Server Action that the access token hasn't expired yet. When it does expire, I perform a signOut from next-auth to log me out and redirect me to the Login page. However, after doing this, the middleware keeps executing and messes up the experience because there's no auth due to the signOut. The middleware also redirects and overwrites the cookies with the reasons for the redirect, which later gets notified to the user on the login page.

If I remove the middleware validation, then when navigating to a page without a user session, it won't redirect to the login. Haha, how can I prevent the middleware from executing if I've already made a redirect!?

3 Replies

Miiddleware will always run @Standard Chinchilla

Which page do you want to redirect to and which page + code does your middleware redirect to and execute?
What you could do, as a fix is redirect to a certain page from your action, and in the middleware just return early if you are on that certain page
@Arinji What you could do, as a fix is redirect to a certain page from your action, and in the middleware just return early if you are on that certain page
Standard ChinchillaOP
I think the problem I'm experiencing, after commenting out almost all the code, is that from the route: /settings/foo I can't redirect to /login, but I can redirect perfectly to /settings/bar. It's as if I can't redirect to a parent route, and this is happening from a Server Action