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

Tags: , , , ,



I created an API endpoint to handle user account creation in my Next.js app, and I am using knex.js to handle my queries, but I still get this error:

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

My code in /pages/api/users/create.js:

import { hash } from 'bcrypt';
import knex from '../../../knex';

export default async function regiterUser(req, res) {
  if (req.method === 'POST') {
    try {
      hash(req.body.password, 10, async function (_, hash) {
        await knex('users').insert({
          name: req.body.name,
          email: req.body.email,
          role: 'user',
          allowed: true,
          password: hash,
        });
        res.end();
      });
    } catch (err) {
      res.status(err).json({});
    }
  } else {
    res.status(405);
  }
}

Answer

actually the bcrypt hash function is an async function, it returns a promise to be either resolved with the encrypted data salt or rejected with an Error.

import knex from '../../../knex';

export default async function regiterUser(req, res) {
  if (req.method === 'POST') {
    try {
      const hashed = await hash(req.body.password, 10);
      await knex('users').insert({
        name: req.body.name,
        email: req.body.email,
        role: 'user',
        allowed: true,
        password: hashed,
      });
      res.status(200).end();
    } catch (err) {
      res.status(err).json({});
    }
  } else {
    res.status(405);
    res.end();
  }
}


Source: stackoverflow