Using HTTPS on localhost in Nuxt

This is a problem that came up recently on the Nuxt Express Template github issues. After some doing I believe I have a good solution on how to accomplish using a local SSL certificate. Always welcome feedback!

To kick off a Patreon I created to discuss web performance and other developer related topics, I started with a video on how to set up the use of a local SSL certificate using Nuxt 1.4.1. Below is the video and code discussed in the video. I'd love to get any feedback. Also feel free to check out all the great perks for joining the WebPerf.Party over at patreon.com/webperfparty.

Command to Create SSL Key and Cert

openssl req \
-newkey rsa:2048 \
-x509 \
-nodes \
-keyout key.pem \
-new \
-out cert.pem \
-subj /CN=localhost \
-reqexts SAN \
-extensions SAN \
-config <(cat /System/Library/OpenSSL/openssl.cnf \
<(printf '[SAN]subjectAltName=DNS:localhost')) \
-sha256 \
-days 3650

Code for server.js

const { Nuxt, Builder } = require( 'nuxt ' )
const app = require( 'express ' )()
const http = require( 'http ' )
const https = require( 'https ' )
const fs = require( 'fs-extra ' )
let server
const isProd = ( process. env. NODE_ENV === 'production ' )
const port = process. env. PORT || 3000
// Prepare for HTTP or HTTPS
if ( process. env. NODE_ENV !== 'production ' ) {
const pkey = fs. readFileSync( './key.pem ' )
const pcert = fs. readFileSync( './cert.pem ' )
const httpsOptions = {
key : pkey,
cert : pcert
}
server = https. createServer(httpsOptions, app)
} else {
server = http. createServer(app)
}
// We instantiate nuxt.js with the options
const config = require( './nuxt.config.js ' )
config. dev = !isProd
const nuxt = new Nuxt(config)
// Render every route with Nuxt.js
app. use( nuxt. render)
function listen () {
// Listen the server
// app.listen(port, '0.0.0.0');
server. listen(port, 'localhost ' )
}
// Build only in dev mode with hot-reloading
if ( config. dev) {
new Builder(nuxt). build()
. then(listen)
. catch(( error) => {
console. error(error)
process. exit( 1)
})
} else {
listen()
}
view raw server.js hosted with ❤ by GitHub