Skip to content

Instantly share code, notes, and snippets.

@theetrain
Created July 16, 2021 16:51
Show Gist options
  • Save theetrain/a74ce0656a0ca967ac20ee2a136226ae to your computer and use it in GitHub Desktop.
Save theetrain/a74ce0656a0ca967ac20ee2a136226ae to your computer and use it in GitHub Desktop.
HTTPS-enabled NextJS server
// NextJS custom server with HTTPS
// Note, you must generate certificates on your own
const express = require('express')
const nextJs = require('next')
const https = require('https')
const fs = require('fs')
const APP_ENV = process.env.APP_ENV || 'development'
const port = parseInt(process.env.PORT, 10) || 3000
const app = nextJs({ dev: APP_ENV === 'development' })
const handle = app.getRequestHandler()
async function start () {
const httpsOptions = {
key: fs.readFileSync('./.cert/key.pem'),
cert: fs.readFileSync('./.cert/cert.pem')
}
// Prepare next.js app
await app.prepare()
const server = express()
server.all('*', handle)
if (process.env.APP_ENV === 'development' && process.env.HTTPS === 'true') {
https.createServer(
httpsOptions,
server
).listen(3000, (error) => {
if (error) {
console.log('error:', error)
} else {
console.log(`Started HTTPS server on ${process.env.APP_DOMAIN}`)
}
})
} else {
server.listen(port, '0.0.0.0', (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
}
}
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment