loading...

Using mkcert in Node.js

tingwei628 profile image Tingwei ・2 min read

This main purpose is to create self signed ssl certificates with mkcert@Subash and write a quick demo locally with Node.js.

Step 1: Install NPM package mkcert

$npm install mkcert

Step 2: Create ca.key and ca.crt

$node_modules/mkcert/src/cli.js create-ca

It generates two files ca.key, ca.crt in node_modules/mkcert/src.

Step 3: Create cert.key and cert.crt

$node_modules/mkcert/src/cli.js create-cert

It generates two files cert.key, cert.crt in node_modules/mkcert/src.

Step 4: For the convenience, copy ca and cert out.

$cp node_modules/mkcert/src/ca.key ./ca.key
$cp node_modules/mkcert/src/ca.cert ./ca.crt
$cp node_modules/mkcert/src/cert.key ./cert.key
$cp node_modules/mkcert/src/cert.crt ./cert.crt

The directory looks like this.

./node_modules
./client.js
./server.js
./ca.key
./ca.crt
./cert.key
./cert.crt

Step 5: Write codes on server side

in server.js

const https = require('https');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3001;

const server = https.createServer({
  key: fs.readFileSync("./cert.key"),
  cert: fs.readFileSync("./cert.crt"),
}, (req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at https://${hostname}:${port}/`);
});

Step 6: Write codes on client side

in client.js

const https = require('https');
const fs = require('fs');
const options = {
  hostname: 'localhost',
  port: 3001,
  method: 'GET',
  ca: fs.readFileSync('./ca.crt'),
};
const req = https.request(options, (res) => {
  res.on('data', (d) => {
    process.stdout.write(d);
  });
}).on('error', (e) => {
  console.error(e);
});
req.end();

Step 7: Start a server

$node server.js

Step 8: Send a request to server

$node client.js

You can send a request with curl. Remember to put --cacert

$curl --cacert ./ca.crt -X GET https://localhost:3001

Thank you!

Discussion

pic
Editor guide