18. Next.js Tutorial (5). Deploying. HTTPS

1. Deploying and running the applications

If you want to execute the application in a Node.js server, as far as I know, follow theses steps: 

1. Execute npm run build, and verify there is no errors.

2. Try to execute the application in the 2 ways:
    2.1 Development mode: npm run dev and
    2.2 Production mode: npm run start
   Verify that the application runs OK in both cases!

3. You must copy all the contents of the project folder (in my case my-app10) to another folder in the server, then, execute npm run start and verify that the application works. But it runs HTTP!

If you want to change the port of the server, change the "start" parameter in the package.json file as follows:

"start": "next start -p $PORT"

where $PORT is the desired port (for instance 3001, 8080 ..)

2. Alternatively running HTTP. Using server.js

After you have copied the development folder to the server, follow these steps:

1. Create the file  server.js in the my-app10 directory

const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const port = 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
createServer({}, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(port, (err) => {
if (err) throw err;
console.log("ready - started server on url: http://localhost:" + port);
});
});

2. Execute npm run build

3. Execute node server.js 

The application is running

3. Alternatively running HTTPS. Using server,js

1. Copy the needed certificate files to the "keystores" folder of the project (my_crt.pem, my_key.pem and my_crt_chained.pem)

2. Create the file  server.js in the my-app10 directory

const { createServer } = require("https");
const { parse } = require("url");
const next = require("next");
const fs = require("fs");
const port = 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

const httpsOptions = {
cert: fs.readFileSync('./keystores/my_crt.pem'), // certificate
key: fs.readFileSync('./keystores/my_key.pem'), // key
ca: fs.readFileSync('./keystores/my_crt_chained.pem') // CA Root chains bundle
};

app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(port, (err) => {
if (err) throw err;
console.log("ready - started server on url: https://localhost:" + port);
});
});

3. Execute npm run build

4. Execute node server.js 

The application is running

Comentarios

Entradas populares de este blog

14. Next.js Tutorial (1)