Next.js Discord

Discord Forum

redirect() in route handler (POST)

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
I am trying to redirect to "/documents" after a user deletes a post and hits this route handler. However, the redirect doesnt seem to be working. The reponse is correct "307 Temporary Redirect" but it doesnt actually redirect. It makes a POST request to "/documents" right after. Any ideas?
import { auth } from "@/auth";
import { ObjectId } from "mongodb";
import clientPromise from "@/lib/mongodb";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

export async function POST(request: Request) {
  const session = await auth();
  if (!session) return new Response("Unauthorized", { status: 401 });

  const { id } = await request.json();

  let deleted = false;
  try {
    const client = await clientPromise;
    const db = client.db("twainGPT");
    const data = await db
      .collection("documents")
      .deleteOne({ _id: new ObjectId(id), owner: session.user?.email });
    deleted = data.deletedCount === 1;
  } catch (e) {
    console.error(e);
    return new Response("Error deleting document", { status: 500 });
  }
  if (!deleted) {
    return new Response("Document not found", { status: 404 });
  }

  revalidatePath("/documents");
  redirect("/documents");
}

16 Replies

@!=tgt try to return the redirect
American black bearOP
doesnt work 😕 same behavior, /delete gives a 307 redirect and then a post request is made to /documents
@American black bear
@!=tgt <@251874315534991371>
American black bearOP
thanks! ill try it out in a bit and let you know
@!=tgt and do res.redirect
American black bearOP
 
export async function POST(request: Request, response: Response) {
...
 response.redirect("/documents");


like this? theres no redirect function on response
American black bearOP
its just a property
idk honestly ill just to the redirect on client side with useRouter
@American black bear its just a property
now that i checked the docs
redirect is the correct way
idk why it's not working tho
American black bearOP
yeah im not sure either, it was working in server actions for me