Run the dev server
node server.jsHTTPS_KEY_PATH and HTTPS_CERT_PATH are custom environment variables.
It is important to access process.env only after app.prepare() call, so it would do the nextjs thing with environment variables first.
| // @ts-check | |
| // server.js | |
| const { createServer } = require("https"); | |
| const fs = require("fs").promises; | |
| const { parse } = require("url"); | |
| const next = require("next").default; | |
| const hostname = "localhost"; | |
| const port = 3000; | |
| const app = next({ dev: true, hostname, port }); | |
| const handle = app.getRequestHandler(); | |
| app.prepare().then(async () => { | |
| // reading env after `Next.prepare()` call | |
| // https://github.com/vercel/next.js/issues/12269#issuecomment-933322120 | |
| const HTTPS_KEY_PATH = process.env.HTTPS_KEY_PATH; | |
| const HTTPS_CERT_PATH = process.env.HTTPS_CERT_PATH; | |
| const key = await fs.readFile(HTTPS_KEY_PATH, { encoding: "utf-8" }); | |
| const cert = await fs.readFile(HTTPS_CERT_PATH, { encoding: "utf-8" }); | |
| const server = createSecureServer({ key, cert }, async (req, res) => { | |
| // Be sure to pass `true` as the second argument to `url.parse`. | |
| // This tells it to parse the query portion of the URL. | |
| const parsedUrl = parse(req.url, true); | |
| await handle(req, res, parsedUrl); | |
| }); | |
| server.listen(port, (err) => { | |
| if (err) throw err; | |
| console.log(`> Ready on https://${hostname}:${port}`); | |
| }); | |
| }); |