Skip to content

Instantly share code, notes, and snippets.

@GabenGar
Created December 3, 2022 02:18
Show Gist options
  • Save GabenGar/078de497f181742fb9a669dd8dcfa130 to your computer and use it in GitHub Desktop.
Save GabenGar/078de497f181742fb9a669dd8dcfa130 to your computer and use it in GitHub Desktop.
NextJS https server
// @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}`);
});
});

Run the dev server

node server.js

HTTPS_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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment