Redirection not changing URL
Unanswered
Yellow and black potter wasp posted this in #help-forum
Yellow and black potter waspOP
Hi y'all. I have created a project to test out this problem I am having where sometimes the redirect does not work as expected or at least not as I understand it.
Say we have a
The login action:
If in
Somewhere I read that this would only change where the answer comes from not the URL, for that that should be done in client but does it? Because as I said, it works fine and the URL changes when the
Thank you so much
Say we have a
redirect/route.ts that looks like:export async function GET(request: NextRequest) {
// user is not logged in
const session = await getSession();
if (!session) {
redirect(`/login?next=${request.nextUrl.pathname}`);
}
redirect("/setup");
}The login action:
"use server";
import { cookies } from "next/headers";
import { encrypt } from "./app/lib";
import { redirect } from "next/navigation";
export async function loginAction(formData: FormData) {
const user = {
username: formData.get("username"),
password: formData.get("password"),
};
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // a week
const session = await encrypt({ user, expires });
cookies().set("session", session, { expires, httpOnly: true });
const redirectTo = formData.get("next") as string;
if (redirectTo) {
redirect(redirectTo);
}
redirect("/dashbord");
}If in
redirect/route.ts I remoe the bit that appends the query param ?next everything works OK, it redirects to /setup without an issue and the URL on client changes, but for some reason even with this simple example when I do add it and create this system that does not forget where it comes from, I find myself with the URL not changing aka it shows /redirect although the content was correctly loaded as /setupSomewhere I read that this would only change where the answer comes from not the URL, for that that should be done in client but does it? Because as I said, it works fine and the URL changes when the
next query param is not considered and a simple redirection is done. Also, tried to change this to middleware and the problem remains the same. Could someone please point to me what is going wrong here?Thank you so much
2 Replies
Yellow and black potter waspOP
Because of character limitation, here is the login page just in case someone wonders how the query param is sent from one place to the other (a hidden input)
The login page:
The login page:
export default function LoginPage({
searchParams,
}: {
searchParams: {
next?: string;
};
}) {
return (
<section>
<form action={loginAction}>
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="next" value={searchParams.next} />
<input type="submit" value="Log in" />
</form>
</section>
);
}Yellow and black potter waspOP
Any help somebody?