Skip to content

Instantly share code, notes, and snippets.

@jimthedev
Created June 22, 2017 01:19
Show Gist options
  • Save jimthedev/0143157fcf2c63b23cb385e405fa9b7e to your computer and use it in GitHub Desktop.
Save jimthedev/0143157fcf2c63b23cb385e405fa9b7e to your computer and use it in GitHub Desktop.
An example micro service using 'micro' that installs an actual development cert to avoid browser SSL errors
const https = require('https')
const { run, send } = require('micro')
const getDevelopmentCertificate = require('devcert-san').default;
async function startServer() {
const PORT = process.env.PORT || 3443;
let ssl;
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
try {
ssl = await getDevelopmentCertificate('my-micro-service');
} catch (e) {
console.error(e);
}
} else {
//ssl = // load production ssl ...
console.log('TODO: prod ssl config');
}
const microHttps = fn => https.createServer(ssl, (req, res) => run(req, res, fn))
const server = microHttps(async (req, res) => {
send(res, 200, { encrypted: req.client.encrypted });
});
server.listen(PORT);
console.log(`\nListening on https://localhost:${PORT}`);
}
startServer().catch(e => console.error(e));
const getDevelopmentCertificate = require('devcert-san').default;
function installCert() {
console.log('If you experience errors, please ensure you\'ve installed the prequisites:');
console.log(' - Mac: brew install nss');
console.log(' - Linux: apt install libnss3-tools');
console.log(' - Windows: N/A');
console.log('');
console.log('NOTE: You may be prompted for your password during initial install.');
getDevelopmentCertificate('my-micro-service', { installCertutil: true }).then(() =>{
console.log('\nSSL cert was installed successfully or already existed.');
}).catch(e => {
console.error('\nError installing cert', e);
});
}
installCert();
{
"name": "my-micro-service",
"version": "1.0.0",
"description": "An example micro service using 'micro' that installs an actual development cert",
"main": "index.js",
"scripts": {
"start": "micro",
"dev": "nodemon ./index.js",
"install-ssl": "node ./installCert.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"micro": "^7.3.3"
},
"devDependencies": {
"devcert-san": "^0.3.3",
"nodemon": "^1.11.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment