API resolved without sending a response in Nextjs
You should return a Promise and resolve/reject it.
Example:
import { getData } from "../../helper";export default async function(req, res) { return new Promise((resolve, reject) => { getData() .then(response => { res.statusCode = 200 res.setHeader('Content-Type', 'application/json'); res.setHeader('Cache-Control', 'max-age=180000'); res.end(JSON.stringify(response)) resolve(); }) .catch(error => { res.json(error); res.status(405).end(); return resolve(); //in case something goes wrong in the catch block (as vijay) commented }); });};
import { getData } from "../../helper";export default async function (req, res) { try { const response = await getData(); res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.setHeader('Cache-Control', 'max-age=180000'); res.end(JSON.stringify(response)); } catch (error) { res.json(error); res.status(405).end(); }}
You can use 'next-connect' library which eliminates the necessity of returning a promise in this scenario. If you like express.js
's route->middleware->endpoint
pattern this library is what you are looking for. It also provides global error handling out of the box! [next-connect docs]
Example:
import nc from 'next-connect'function onError(err, req, res, next) { logger.log(err); res.status(500).end(err.toString()); // OR: you may want to continue next();}const handler = nc({ onError });handler .use((req, res, next) => { if(!req.user){ throw new Error("oh no!"); // or use next next(Error("oh no")); } }) .get((req, res) => { res.end("success") })