Chen Yang

Set Headers Error with Next.js or Express

When I wrote a server API with Next.js, I encountered this error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.

The Problem

This is the simplified version of my code:

// /api/user/me

export default async function handler(req, res) {
  const { id } = req.params;

  // check whether there's this user in database
  const verified = checkIdWithDatabase(id);

  if (verified) {
    res.status(200).json({ authenticated: true });
  }

  res.status(200).json({ authenticated: false });
}

The problem in this code is: the code executes TWO res.json(...), because there's no return after the user's id is verified and true the code executes the "scenario 1️", then it execute "scenario 2️", too. That's why the error says "Cannot ... after they are sent to the client", the "scenario 1️" is already send to the client.

The Solution

Solution 1: only get one result from a condition by using if ... else:

// other parts are omitted

if (verified) {
  res.status(200).json({ authenticated: true });
} else {
  res.status(200).json({ authenticated: false });
}

Solution 2: add return statement:

// other parts are omitted

if (verified) {
  // 1️⃣
  return res.status(200).json({ authenticated: true });
}

res.status(200).json({ authenticated: false });

// ============== OR ================

if (verified) {
  // 2️⃣
  res.status(200).json({ authenticated: true });
  return;
}

res.status(200).json({ authenticated: false });

These solutions can be applied to Express.