NextJS 14, set cookie and redirect not working
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I'm trying to handle a basic prompt for password and login type application. I would like to set a cookie, then redirect the client to a new URL.
I am able to set the cookie, but I'm not able to get a redirect to work in any condition.
The form's submit function is below:
The following is the route handler for /app/api/auth. I am able to set a cookie in the two cases where I try it, but I am not able to execute a redirect at all.
I've truncated this post to meet a message limit, but my tests with setting cookies are in the github repo https://github.com/timatlee/nextjs_redirect_testing. I can set cookies, but not able to redirect.
I am able to set the cookie, but I'm not able to get a redirect to work in any condition.
The form's submit function is below:
// /app/page.tsx
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/auth', {
method: 'POST',
body: formData
})
setSuccess(response.status);
}The following is the route handler for /app/api/auth. I am able to set a cookie in the two cases where I try it, but I am not able to execute a redirect at all.
// /app/api/auth/route.ts
export const runtime = 'edge';
import { NextRequest, NextResponse } from 'next/server'
import { redirect } from 'next/navigation';
import { useRouter } from 'next/navigation'
export async function POST(request: Request) {
const data = await request.formData();
// This doesn't redirect, but should
// https://nextjs.org/docs/app/api-reference/functions/redirect
console.log("do a redirect")
redirect("/admin")
}I've truncated this post to meet a message limit, but my tests with setting cookies are in the github repo https://github.com/timatlee/nextjs_redirect_testing. I can set cookies, but not able to redirect.
Answered by Anay-208