Skip to main content

how to solve “error unhandledRejection - Error [ERR_HTTP_HEADERS_SENT] - Cannot set headers after they are sent to the client”

when you develop using next.js and node, then you often face this error

error unhandledRejection: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

what is that?

SOLUTION

this is often caused by multiple response in node server handler

this is an example

i didn’t return response like this

// /pages/api/movies.ts

import clientPromise from "../../lib/mongodb";

export default async (req: any, res: any) => {
try {
const client = await clientPromise;
const db = client.db("test");
const collection = db.collection("movies");

switch (req.method) {
case "POST":
await collection.insertOne(req.body.movie);
res.status(200).json("work");

case "GET":
collection.find({}).toArray((err, document) => {
if (err) {
res.status(400).json({ err });
}

res.status(200).json(document);
});
}
} catch (err) {
console.log("handler ERROR", err);
res.status(500).json("handle /api/movies ERROR");
}
};

then it occurs this error

error unhandledRejection: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

and when i deploy to vercel, if i call POST method, then it return 500 error page.

so this is solution

// pages/api/movies.ts

import clientPromise from "../../lib/mongodb";

export default async (req: any, res: any) => {
try {
const client = await clientPromise;
const db = client.db("test");
const collection = db.collection("movies");

switch (req.method) {
case "POST":
await collection.insertOne(req.body.movie);
return res.status(200).json("work");

case "GET":
collection.find({}).toArray((err, document) => {
if (err) {
return res.status(400).json({ err });
}

return res.status(200).json(document);
});
}
} catch (err) {
console.log("handler ERROR", err);
return res.status(500).json("handle /api/movies ERROR");
}
};

after applying this ‘return’ keyword, i didn’t get that error