title: Express 404: "Cannot set headers after they are sent to the client"
body: <p>I am working on a Node/Express app and I would like it to return a 404 page if a promise function does not resolve. </p>
  
  <p>This is how I'm trying to do it:</p>
  
  <pre><code>app.get("/projects", t("projects", function(req, res) {
      res.header("Cache-Control", "private, max-age=0, no-cache, no-store");
      return projects.list(req.user, req.query)
          .then((projects) =&gt; (Object.assign(projects, { company_name: req.user.company_name })))
          .catch(() =&gt; res.status("404").send(""));
  }));
  </code></pre>
  
  <p>Unfortunately this crashes my app with the error <code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client</code>.</p>
  
  <p>How can I make this so it 404s without crashing the app, if and only if the promise rejects?</p>
  
  <p>For the record, the <code>projects.list</code> function is very simple, it just makes a database call and returns an object.</p>
  
  <pre><code>function list(user, query_params) {
      const folder = query_params.folder || "all";
      return entity.User.listedProjects(user.id, filter_by)
          .then((projects) =&gt; {
              if (folder !== null &amp;&amp; !projects.some(t =&gt; t.current)) {
                  return Promise.reject();
              }
              return {
                  "projects": projects,
                  "active_folder": folder
              };
          });
  }
  </code></pre>
  
  <p>UPDATE: as requested, here's the <code>t</code> function:</p>
  
  <pre><code>function t(template_name, get_additional_params, options={}) {
      return function(req, res) {
          if (!req.user &amp;&amp; !options.do_not_require_login) return res.redirect("/login?redirect=" + encodeURIComponent(req.originalUrl));
  
          if (!get_additional_params) {
              get_additional_params = (() =&gt; Promise.resolve({}));
          }
  
          get_additional_params(req, res)
              .then(function(additional_params) {
                  if (additional_params &amp;&amp; "_redirect" in additional_params) {
                      return res.redirect(additional_params._redirect);
                  }
  
                  const standard_params = {
                      "error": req.flash("error"),
                  };
  
                  const params = Object.assign({}, additional_params, standard_params);
                  res.render(template_name + ".html", params);
              })
              .catch(utils.fail(req, res));
      };
  }
  </code></pre>