Next.js Discord

Discord Forum

route.js error handling

Unanswered
Knospak posted this in #help-forum
Open in Discord
I want to catch the 'username or password is incorrect' error returned by the API when the user enters the wrong password or username as rejected in redux, how do I return the response as an error?

import { NextResponse } from "next/server";

export async function POST(request) {
  let response = new NextResponse();
  const { username, password } = await request.json();
  try {
    const res = await fetch("https://fakestoreapi.com/auth/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        username: username,
        password: password,
      }),
    });

    if (res.status === 401) {
      const errorText = await res.text();
      return NextResponse.json({ error: errorText }, { status: 401 });
    }

    const data = await res.json();
    response.cookies.set("token", data.token);
    response.cookies.set("id", 1);
    return response;
  } catch (error) {
    throw error;
  }
}

2 Replies

@Knospak your code seems ok. indeed it returns(forward) HTTP status 401 authentication error, meaning user id and password is not correct. one thing is, you want to return an HTTP response instead of throw error inside catch.
How is Redux, client side, realted to this question?
another thing is your cookie token is accessible from client side js so you want to add httpOnly tag.
headers['Set-Cookie'] = `token=${token}; path=/; HttpOnly; SameSite=Strict`;

just my two cents