Setting Up Local Development Environment
For local development, it is crucial to configure your local environment to serve the content via HTTPS. This can be easily achieved by generating a certificate for your localhost by following these steps:
Step 1: Create a Certificates Folder
In your project root, create a new folder namedcertificates
.Step 2: Generate a Certificate
Use the following command to generate a certificate inside thecertificates
folder for localhost:openssl req -x509 -out localhost.crt -keyout localhost.key \
-days 365 \
-newkey rsa:2048 -nodes -sha256 \
-subj '/CN=localhost' -extensions EXT -config <( \
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")
Step 3: Add Certificate to Keychain
Find the createdlocalhost.crt
certificate and double-click it to add it to your Keychain. Adjust the preferences to always trust this certificate.Step 4: Create Server.js File
At the root of your project, create aserver.js
file. Note that the code will vary depending on the framework you're using. The example code for NextJS with React is given below:const { createServer } = require("https");
const { parse } = require("url");
const next = require("next");
const fs = require("fs");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const httpsOptions = {
key: fs.readFileSync("./certificates/localhost.key"),
cert: fs.readFileSync("./certificates/localhost.crt"),
};
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(3000, (err) => {
if (err) throw err;
console.log("> Server started on https://localhost:3000");
});
});
Step 5: Run the Server with HTTPS
Executenpm run https
. Make sure to add the following code to package.json before executing the command: "https": "node server.js"