Reading List
Libraries
Developer Resources
Reading List
A starter code to set up a local development server using express.js, for vanilla JavaScript project.
The following setup is suitable for when you want to:
host an application in the same port, e.g.
localhost:8000,host multiple versions of application, e.g. a development and production setup.
host the app in secure context (https).
Takeaway Code
The following setup will serve src folder on localhost:8000.
Directory structure:
/src
index.html
package.json
server.jspackage.json
{
"type": "module",
"devDependencies": {
"express": "^4.21.1"
}
}server.js
import express from 'express';
let servers = [
{ port: 8000, dir: 'src/', },
];
// Start servers
console.log('Servers running at:');
for (let server of servers) {
let {port, dir} = server;
let app = express();
app.use(express.static(dir));
app.listen(port, () => {
console.log(`${dir}: http://localhost:${port}/`);
});
}Running the Project
Install dependencies using pnpm:
pnpm iTo start the server, run:
node serverCustomization
Secure Context (HTTPS)
Refer to the following article:
In summary, you need to:
install
mkcert,generate certificate in you PC and distribute it on devices that want to access the secure context,
generate
.pemfiles in the project folder (also, ignore it in git), e.g:
mkcert localhost 192.168.1.90use the following
server.jssetup:
import express from 'express';
import https from 'https';
import fs from 'fs';
// Server configuration
let servers = [
{ port: 8207, dir: 'src/', isHttps: true },
// { port: 3000, dir: 'dist/', },
];
// Start servers
for (let server of servers) {
let { port, dir, isHttps, staticPath } = server;
let app = express();
app.use(express.static(dir));
if (isHttps) {
// HTTPS server (using same port)
const httpsOptions = {
key: fs.readFileSync('localhost+1-key.pem'), // Replace with the actual key file
cert: fs.readFileSync('localhost+1.pem'), // Replace with the actual cert file
};
const httpsServer = https.createServer(httpsOptions, app);
httpsServer.listen(port, () => {
// HTTPS on a different port to avoid conflict
console.log(`HTTPS server running at: https://localhost:${port}/`);
});
} else {
app.listen(port, () => {
console.log(`${dir}: http://localhost:${port}/`);
});
}
}
https://www.blogger.com/comment/fullpage/post/8166404610182826392/1235081772532359779
true