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

Viewed 11920

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);
  }
}
3 Answers

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();
  }
}

In the else block of if statement res.end() must be called.

} else {
  res.status(500)
  res.end()
}

To make API response clearer, consider using 405 status code instead of 500 in this case. 405 means method is not allowed (see here).

Just make sure it is an async function and the add:

res.status(200) // for success
res.status(500) // enter code here`for failed
Related