How to generate a local SSL certificate

Note: I ran these commands on macOS. Linux should work in the same way. I do not guarantee the use of Windows.

In the project root folder, run:

openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

Now run:

openssl rsa -in keytmp.pem -out key.pem

You should now have the filecert.pemwithkey.pemIn the folder.

With Express/Node.js, you can use the following code to load the certificate and key:

const fs = require('fs')
const https = require('https')
const app = express()

app.get(’/’, (req, res) => { res.send(‘Hello HTTPS!’) })

https.createServer({ key: fs.readFileSync(‘key.pem’), cert: fs.readFileSync(‘cert.pem’) }, app).listen(3000, () => { console.log(‘Listening…’) })

If you are usingcreate-react-app,changestartScript inpackage.jsonArchive to:

"start": "export HTTPS=true&&SSL_CRT_FILE=cert.pem&&SSL_KEY_FILE=key.pem react-scripts start",

Look at your framework/library documentation on the instructions on how to pass the certificate and key to the app.


More network tutorials: