Skip to content

Instantly share code, notes, and snippets.

@sacru2red
Last active January 7, 2023 02:34
Show Gist options
  • Save sacru2red/2e0013a94ddc01a0d6cdfac7968f9865 to your computer and use it in GitHub Desktop.
Save sacru2red/2e0013a94ddc01a0d6cdfac7968f9865 to your computer and use it in GitHub Desktop.
next patch ssl

It's for users having ssl files (crt.pem, key.pem)

If you are coding development env, edit 'hosts' file

Like

127.0.0.1    localhost ... local.mydomain.com  ...
  1. install patch-package

npm

npm install --save patch-package

yarn

yarn add patch-package postinstall-postinstall

refer

  1. add a patch file

make to project root

project-root/patches/next+12.3.1.patch

and paste it

diff --git a/node_modules/next/dist/cli/next-dev.js b/node_modules/next/dist/cli/next-dev.js
index 5c7a7e7..cc9405c 100644
--- a/node_modules/next/dist/cli/next-dev.js
+++ b/node_modules/next/dist/cli/next-dev.js
@@ -64,10 +64,12 @@ const nextDev = (argv)=>{
         "--help": Boolean,
         "--port": Number,
         "--hostname": String,
+        "--ssl": Boolean,
         // Aliases
         "-h": "--help",
         "-p": "--port",
-        "-H": "--hostname"
+        "-H": "--hostname",
+        "-s": "--ssl"
     };
     let args;
     try {
@@ -96,6 +98,7 @@ const nextDev = (argv)=>{
         --port, -p      A port number on which to start the application
         --hostname, -H  Hostname on which to start the application (default: 0.0.0.0)
         --help, -h      Displays this message
+        --ssl, -s       run Server with ssl protocol
     `);
         process.exit(0);
     }
@@ -126,15 +129,39 @@ const nextDev = (argv)=>{
     // We do not set a default host value here to prevent breaking
     // some set-ups that rely on listening on other interfaces
     const host = args["--hostname"];
+    const runningWithSSL = args['--ssl'];
+    if (runningWithSSL) {
+        const checkExistsSSLDir = _fs.existsSync(_path.default.join(dir, 'ssl'));
+        const requireFilesSSL = ['key.pem', 'crt.pem', 'chain.pem'];
+        if (!checkExistsSSLDir) {
+            console.log(`
+                if you want to run with ssl,
+                make 'ssl' directory at project root
+                and put ${requireFilesSSL.join(', ')}
+            `);
+            process.exit(0);
+        };
+        const existsFiles = requireFilesSSL.every((f) => {
+            return _fs.existsSync(_path.default.join(dir, 'ssl', f))
+        });
+        if (!existsFiles) {
+            console.log(`
+                put ${requireFilesSSL.join(', ')} into 'ssl' directory,
+            `);
+            process.exit(0);
+        };
+    };
     (0, _startServer).startServer({
         allowRetry,
         dev: true,
         dir,
         hostname: host,
         isNextDevCommand: true,
-        port
+        port,
+        runningWithSSL
     }).then(async (app)=>{
-        const appUrl = `http://${app.hostname}:${app.port}`;
+        const protocol = runningWithSSL ? 'https' : 'http'
+        const appUrl = `${protocol}://${app.hostname}:${app.port}`;
         (0, _output).startedDevelopmentServer(appUrl, `${host || "0.0.0.0"}:${app.port}`);
         // Start preflight after server is listening and ignore errors:
         preflight().catch(()=>{});
diff --git a/node_modules/next/dist/cli/next-start.js b/node_modules/next/dist/cli/next-start.js
index 128f3b0..1e41fda 100644
--- a/node_modules/next/dist/cli/next-start.js
+++ b/node_modules/next/dist/cli/next-start.js
@@ -5,6 +5,8 @@ Object.defineProperty(exports, "__esModule", {
 });
 exports.nextStart = void 0;
 var _indexJs = _interopRequireDefault(require("next/dist/compiled/arg/index.js"));
+var _fs = require("fs");
+var _path = _interopRequireDefault(require("path"));
 var _startServer = require("../server/lib/start-server");
 var _utils = require("../server/lib/utils");
 var Log = _interopRequireWildcard(require("../build/output/log"));
@@ -61,10 +63,12 @@ const nextStart = (argv)=>{
         "--port": Number,
         "--hostname": String,
         "--keepAliveTimeout": Number,
+        "--ssl": Boolean,
         // Aliases
         "-h": "--help",
         "-p": "--port",
-        "-H": "--hostname"
+        "-H": "--hostname",
+        "-s": "--ssl"
     };
     let args;
     try {
@@ -94,6 +98,7 @@ const nextStart = (argv)=>{
         --hostname, -H  Hostname on which to start the application (default: 0.0.0.0)
         --keepAliveTimeout  Max milliseconds to wait before closing inactive connections
         --help, -h      Displays this message
+        --ssl, -s       run Server with ssl protocol
     `);
         process.exit(0);
     }
@@ -105,13 +110,37 @@ const nextStart = (argv)=>{
         (0, _utils).printAndExit(`Invalid --keepAliveTimeout, expected a non negative number but received "${keepAliveTimeoutArg}"`, 1);
     }
     const keepAliveTimeout = keepAliveTimeoutArg ? Math.ceil(keepAliveTimeoutArg) : undefined;
+    const runningWithSSL = args['--ssl'];
+    if (runningWithSSL) {
+        const checkExistsSSLDir = _fs.existsSync(_path.default.join(dir, 'ssl'));
+        const requireFilesSSL = ['key.pem', 'crt.pem', 'chain.pem'];
+        if (!checkExistsSSLDir) {
+            console.log(`
+                if you want to run with ssl,
+                make 'ssl' directory at project root
+                and put ${requireFilesSSL.join(', ')}
+            `);
+            process.exit(0);
+        };
+        const existsFiles = requireFilesSSL.every((f) => {
+            return _fs.existsSync(_path.default.join(dir, 'ssl', f))
+        });
+        if (!existsFiles) {
+            console.log(`
+                put ${requireFilesSSL.join(', ')} into 'ssl' directory,
+            `);
+            process.exit(0);
+        };
+    };
     (0, _startServer).startServer({
         dir,
         hostname: host,
         port,
-        keepAliveTimeout
+        keepAliveTimeout,
+        runningWithSSL
     }).then(async (app)=>{
-        const appUrl = `http://${app.hostname}:${app.port}`;
+        const protocol = runningWithSSL ? 'https' : 'http'
+        const appUrl = `${protocol}://${app.hostname}:${app.port}`;
         Log.ready(`started server on ${host}:${app.port}, url: ${appUrl}`);
         await app.prepare();
     }).catch((err)=>{
diff --git a/node_modules/next/dist/server/lib/start-server.js b/node_modules/next/dist/server/lib/start-server.js
index ef6e2fd..3b0cc7b 100644
--- a/node_modules/next/dist/server/lib/start-server.js
+++ b/node_modules/next/dist/server/lib/start-server.js
@@ -5,7 +5,12 @@ Object.defineProperty(exports, "__esModule", {
 exports.startServer = startServer;
 var _log = require("../../build/output/log");
 var _http = _interopRequireDefault(require("http"));
+var _https = _interopRequireDefault(require("https"));
 var _next = _interopRequireDefault(require("../next"));
+var _fs = require("fs");
+var _path = _interopRequireDefault(require("path"));
+var _getProjectDir = require("../../lib/get-project-dir");
+
 function _interopRequireDefault(obj) {
     return obj && obj.__esModule ? obj : {
         default: obj
@@ -13,12 +18,23 @@ function _interopRequireDefault(obj) {
 }
 function startServer(opts) {
     let requestHandler;
-    const server = _http.default.createServer((req, res)=>{
-        return requestHandler(req, res);
-    });
+    let server;
+    if (opts.runningWithSSL) {
+        server = _https.default.createServer({
+            key: _fs.readFileSync(_path.default.join(opts.dir, 'ssl', 'key.pem')),
+            cert: _fs.readFileSync(_path.default.join(opts.dir, 'ssl', 'crt.pem')),
+            ca: _fs.readFileSync(_path.default.join(opts.dir, 'ssl', 'chain.pem')),
+        }, (req, res)=>{
+            return requestHandler(req, res);
+        });
+    } else {
+        server = _http.default.createServer((req, res)=>{
+            return requestHandler(req, res);
+        });
+    };
     if (opts.keepAliveTimeout) {
         server.keepAliveTimeout = opts.keepAliveTimeout;
-    }
+    };
     return new Promise((resolve, reject)=>{
         let port = opts.port;
         let retryCount = 0;

  1. apply patch
npm install
yarn install
  1. add pem files

project-root/ssl/key.pem

project-root/ssl/crt.pem

  1. edit script

before

...
"dev": "next dev",
...
"start": "next start",
...

after

...
"dev": "next dev --hostname local.mydomain.com -p 443 -s",
...
"start": "next start --hostname local.mydomain.com -p 443 -s",
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment