Next.js Discord

Discord Forum

No response return from Route Handler with API routes

Answered
Blue horntail woodwasp posted this in #help-forum
Open in Discord
Blue horntail woodwaspOP
I have an api routes for sending a logout request to my backend (to delete their access token).

I am using axios for sending request since have a bad experience with fetch.

here is my Route Handler on api route :
export async function POST(request: Request) {
  const token = cookies().get("token");
  await axios
    .post(
      `${process.env.API_URL}/logout`,
      {},
      {
        headers: {
          Authorization: `Bearer ${token?.value}`,
        },
      }
    )
    .then((res) => {
      console.log({ res });
      cookies().delete("token");
      return NextResponse.json({
        message: "Logout success!",
      });
    })
    .catch((err) => {
      console.log({ err });

      throw new Error("Logout failed!");
    });
}


And I call this in my client component :
 const logout = async (e: FormEvent<HTMLFormElement>) => {
    setLoading(true);
    e.preventDefault();
    const res = await fetch("/api/auth/logout", {
      method: "POST",
    }).finally(() => setLoading(false));

    if (res.ok) {
      signOut();
    }
  };

Am I doing it wrong?
Answered by Blue horntail woodwasp
Solve by move out thereturn NextResponse.json() from axios.then() and put at the bottom of my function :
export async function POST() {
  const token = cookies().get("token");
  await axios
    .post(
      `${process.env.API_URL}/logout`,
      {},
      {
        headers: {
          Authorization: `Bearer ${token?.value}`,
        },
      }
    )
    .catch((err) => {
      console.log({ err });

      throw new Error("Logout failed!");
    });
  cookies().delete("token");
  return NextResponse.json({
    message: "Logout success!",
  });
}
View full answer

4 Replies

Blue horntail woodwaspOP
Here is my response on console :
 ⨯ Error: No response is returned from route handler 'C:my-directory\app\api\auth\logout\route.ts'. Ensure you return a `Response` or a `NextResponse` in all branches of your handler.
Also I have success to console.log the response if the request succeded.
and some how my token cookies not deleted
Blue horntail woodwaspOP
Solve by move out thereturn NextResponse.json() from axios.then() and put at the bottom of my function :
export async function POST() {
  const token = cookies().get("token");
  await axios
    .post(
      `${process.env.API_URL}/logout`,
      {},
      {
        headers: {
          Authorization: `Bearer ${token?.value}`,
        },
      }
    )
    .catch((err) => {
      console.log({ err });

      throw new Error("Logout failed!");
    });
  cookies().delete("token");
  return NextResponse.json({
    message: "Logout success!",
  });
}
Answer