Why NextResponse.redirect is not triggering on production #68767
-
SummaryI want to implement a simple login flow. I have a login form that takes the user's phone and password. The credentials are sent to the API after submitting the form by calling the const { login, isLoggingIn } = useLogin();
const router = useRouter()
const onSubmit = ({ phone, password }) => {
login(
{ phone, password },
{
onSuccess: ({ data: { token } }) => {
setCookie("token", token);
router.push('/projects')
},
}
);
}; For protecting my routes, I use middleware: import { getCookie } from "cookies-next";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export const config = {
matcher: "/((?!api|_next/static|_next/image|assets|favicon.ico|verify-email).*)",
};
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const token = getCookie("token", { req, res });
const isAuthRoute = req.nextUrl.pathname === "/auth";
if (!token && !isAuthRoute) {
return NextResponse.redirect(new URL("/auth", req.url));
}
if (token && isAuthRoute) {
return NextResponse.redirect(new URL("/projects", req.url));
}
return res;
} The code works perfectly without any issues on development (http://localhost:3000/). The user fills out the form, the form gets submitted and form data is sent to the API. The API responds back with the token. The token gets set in the browser's cookies and user gets redirected successfully. The issue occurs when I push the code to production and also when I run Then if you wait for about 30 seconds and submit the form again, the page gets redirected successfully this time! Also, if you Refresh the page after the first submit, since the token is set to cookies, the page gets redirected to These are what I've tried so far to solve the issues:
I must mention that I use:
Note: My Edit: I removed the whole I appreciate any help anyone could kindly provide. Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Did you make this work? I have a similar issue. |
Beta Was this translation helpful? Give feedback.
-
I have a similar issue, but what I'm dealing with is that if the user performs a server action, this will trigger the middleware, and if the token is expired, because you are accessing a "protected" route, in the middleware, I have a |
Beta Was this translation helpful? Give feedback.
Hey Thanks!
I did fix the problem I had, it had to do with an
<a>
withhref
link usingwww
in the address, instead I just wenthref="htttps://mysite.com"
<--- this was to reach a route that had aNextResponse.redirect(new URL("https://heregoestheothersite.com", req.url));