DEV Community

Tingwei
Tingwei

Posted on

 

Using mkcert in Node.js

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
Enter fullscreen mode Exit fullscreen mode

Step 2: Create ca.key and ca.crt

$node_modules/mkcert/src/cli.js create-ca
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The directory looks like this.

./node_modules
./client.js
./server.js
./ca.key
./ca.crt
./cert.key
./cert.crt
Enter fullscreen mode Exit fullscreen mode

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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Step 7: Start a server

$node server.js
Enter fullscreen mode Exit fullscreen mode

Step 8: Send a request to server

$node client.js
Enter fullscreen mode Exit fullscreen mode

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

$curl --cacert ./ca.crt -X GET https://localhost:3001
Enter fullscreen mode Exit fullscreen mode

Thank you!

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.