Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Created July 3, 2020 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardocanelas/56936582d13a697ffdfd347bcb49eac6 to your computer and use it in GitHub Desktop.
Save ricardocanelas/56936582d13a697ffdfd347bcb49eac6 to your computer and use it in GitHub Desktop.
Https with Next.js
const { createServer } = require('https')
const { parse } = require('url')
const next = require('next')
const selfsigned = require('selfsigned')
// const fs = require('fs')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const attrs = [{ name: 'commonName', value: 'localhost' }]
const pems = selfsigned.generate(attrs, { days: 365 })
// save rootCA.cert and add it in chrome://settings
// https://support.google.com/chrome/a/answer/6342302?hl=pt-BR
// fs.writeFileSync('./certificate.crt', pems.cert)
const httpsOptions = {
host: 'localhost',
key: pems.private,
cert: pems.cert,
}
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
}).listen(3000, (err) => {
if (err) throw err
console.log('> Ready on https://localhost:3000')
})
})
// resources:
// - https://support.securly.com/hc/en-us/articles/212134628
// - https://github.com/jfromaniello/selfsigned/issues/13
// - https://nodejs.org/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server/
// - https://flaviocopes.com/express-https-self-signed-certificate/
// - https://github.com/jfromaniello/selfsigned
// - https://github.com/FiloSottile/mkcert/
// - https://gist.github.com/cecilemuller/9492b848eb8fe46d462abeb26656c4f8
// - https://github.com/vercel/next.js/discussions/10935
// - https://medium.com/@anMagpie/secure-your-local-development-server-with-https-next-js-81ac6b8b3d68
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment