Skip to content

Instantly share code, notes, and snippets.

@NBprojekt
Last active February 2, 2022 09:13
Show Gist options
  • Save NBprojekt/ff02f92bedfc00dc776775339850070c to your computer and use it in GitHub Desktop.
Save NBprojekt/ff02f92bedfc00dc776775339850070c to your computer and use it in GitHub Desktop.

SPA Webserver

This is the webserver configuration I use local for production preview or inside docker container, mostly to host angular apps.

Configuration

You can configure the server, changing the values of the config object.

// TODO: Add attribute table with default values and description

Dependencies

// Imports
const fs = require('fs');
const https = require('https');
const http = require('http');
const express = require('express');
const compression = require('compression');
const app = express();
// Config
const config = {
appFolder: `${__dirname}/www`,
forceHttps: false,
hostName: 'localhost',
ports: {
http: 9080,
https: 9443,
},
credentials: {
key: `${__dirname}/certificates/ssl.key`,
cert: `${__dirname}/certificates/ssl.crt`,
},
};
// Add file compression
app.use(compression());
// Add optional https redirect
app.use((req, res, next) => {
if (!config.forceHttps || req.secure) {
next()
} else {
res.redirect(`https://${req.hostname}:${config.ports.https}${req.url}`);
}
});
// Set up redirects for single page app
if (!fs.existsSync(config.appFolder) || !fs.existsSync(`${config.appFolder}/index.html`)) {
console.error('App folder or index.html do not exist');
return;
}
app.get('*.*', express.static(config.appFolder, {
maxAge: '1m',
}));
app.get('*', (_req, res) => {
res.status(200).sendFile(`/`, {
root: config.appFolder,
});
});
// Create servers
http.createServer(app)
.listen(config.ports.http, config.hostName, () => {
console.log(`Http server started ${config.hostName}:${config.ports.http}`);
});
if (fs.existsSync(config.credentials.key) && fs.existsSync(config.credentials.cert)) {
https.createServer({
key: fs.readFileSync(config.credentials.key, 'utf8'),
cert: fs.readFileSync(config.credentials.cert, 'utf8'),
}, app)
.listen(config.ports.https, config.hostName, () => {
console.log(`Https server started ${config.hostName}:${config.ports.http}`);
});
} else {
console.warn('Https certificates are not available');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment