title: How do I use a self signed certificate for a HTTPS Node.js server?
body: <p>I have started writing a wrapper for an API which requires all requests to be over HTTPS. Instead of making requests to the actual API while I am developing and testing it I would like to run my own server locally which mocks the responses.</p>
  
  <p>I am confused about how to generate the certificates I need to create a HTTPS server and send requests to it.</p>
  
  <p>My server looks something like this:</p>
  
  <pre><code>var options = {
    key: fs.readFileSync('./key.pem'),
    cert: fs.readFileSync('./cert.pem')
  };
  
  https.createServer(options, function(req, res) {
    res.writeHead(200);
    res.end('OK\n');
  }).listen(8000);
  </code></pre>
  
  <p>The pem files were generated with:</p>
  
  <pre><code>openssl genrsa 1024 &gt; key.pem
  openssl req -x509 -new -key key.pem &gt; cert.pem
  </code></pre>
  
  <p>And a request looks something like this:</p>
  
  <pre><code>var options = {
    host: 'localhost',
    port: 8000,
    path: '/api/v1/test'
  };
  
  https.request(options, function(res) {
    res.pipe(process.stdout);
  }).end();
  </code></pre>
  
  <p>With this setup I get <code>Error: DEPTH_ZERO_SELF_SIGNED_CERT</code>, so I think I need to add a <code>ca</code> option for the request.</p>
  
  <p>So my question is how should I generate the following:</p>
  
  <ol>
  <li>The server <code>key</code>?</li>
  <li>The server <code>cert</code>?</li>
  <li>The <code>ca</code> for the request?</li>
  </ol>
  
  <p>I have read a few things about generating self signed certificates with openssl, but can't seem to wrap my head around it and figure out which keys and certificates to use where in my node code.</p>
  
  <p><strong>Update</strong></p>
  
  <p>The API provides a CA certificate to use instead of the defaults. The following code works using their certificate and this is what I want to reproduce locally.</p>
  
  <pre><code>var ca = fs.readFileSync('./certificate.pem');
  
  var options = {
    host: 'example.com',
    path: '/api/v1/test',
    ca: ca
  };
  options.agent = new https.Agent(options);
  
  https.request(options, function(res) {
    res.pipe(process.stdout);
  }).end();
  </code></pre>