Cholewka
Cholewka

Reputation: 983

Next.js's API route does not send response

Next.js sends this error when requesting my API route:

API resolved without sending a response for /api/login, this may result in stalled requests.

The content of the API route is, I guess, valid. Most edgecases was solved. I'll also add that the error was occuring when successfully logged.

 export default withSession(async (req, res) => {
    if (req.method !== "POST") {
        return res.status(405).send({ error: "Tylko metoda POST jest dozwolona." });
    }

    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(401).send({ error: "Nazwa użytkownika i hasło nie mogą być puste." });
    }

    try {
        const knex = getKnex();
        const user = await knex<User>("users").select("*").where("username", username).first();

        if (!user) {
            return res.status(401).send({ error: "Użytkownik o takiej nazwie nie istnieje." });
        }

        bcrypt.compare(password, user.password, async function (error) {
            if (error) {
                return res.status(403).send({ error: "Podane hasło jest nieprawidłowe." });
            }

            const { password, ...result } = user;
            req.session.set("user", result);

            await req.session.save();
            res.status(200).send({ message: "Zostałeś zalogowany." });
        });
    } catch (error) {
        res.status(error?.status || 500).send({ error: error.message });
        console.error(error.stack);
    }
});

The withSession function is a utility for handling next-iron-session.

Upvotes: 1

Views: 2143

Answers (2)

enoch
enoch

Reputation: 3123

You can delete this warning by exporting a config object to change the default configs.

it tells the server that this route is being handled by an external resolver

export const config = {
  api: {
    externalResolver: true,
  },
}

reference

Upvotes: 0

Aviad
Aviad

Reputation: 3584

Attempt to add a return before calling the bcrypt and on its final response, such as:

        return bcrypt.compare(password, user.password, async function (error) {
            if (error) {
                return res.status(403).send({ error: "Podane hasło jest nieprawidłowe." });
            }

            const { password, ...result } = user;
            req.session.set("user", result);

            await req.session.save();
            return res.status(200).send({ message: "Zostałeś zalogowany." });
        });

Upvotes: 1

Related Questions