browsersync + http2 + compression over https://localhost - node.js

Trying to init browsersync with https, http2 and gzip, but can never seem to get them all to play nicely together
var gulp = require('gulp');
var browserSync = require('browser-sync');
var compression = require('compression');
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "dist",
middleware: [compression()]
},
httpModule: 'http2',
https: {
key: "/path/to/localhost.key",
cert: "/path/to/localhost.crt"
}
})
})
I can get http2 to work without compression, and compression to work without http2, but never both at the same time... The error I get is
Error: Can't set headers after they are sent.
Doing the same thing using express was successful
var express = require('express');
var http2 = require('spdy');
var serveStatic = require('serve-static');
var compression = require('compression');
var credentials = {
key: "/path/to/localhost.key",
cert: "/path/to/localhost.crt"
};
var app = express();
app.use(compression())
app.use(serveStatic('./dist', {
'extensions': ['html'],
'maxAge': 3600000
}))
var httpsServer = http2.createServer(credentials, app);
httpsServer.listen(8888);
But no joy using browsersync
Any help, much appreciated.

Related

How can i connect to node server with letsencrypt https activated

I have a problem since i activated letsencrypt on my domain and did'nt have problem with http server before.
Here is my app.js code:
var app = require('express')();
var fs = require('fs');
var https = require('https');
var secureServer = https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert'),
ca: fs.readFileSync('server.cacert'),
requestCert: true,
rejectUnauthorized: false
}, app).listen(5221, function() {
console.log("Secure Express server listening on port "+ 5221);
});
var io = require('socket.io')(secureServer);
The Secure Express server listening on port 5221 prints out but nothing more and the codes in:
io.on('connection', function (socket) {
console.log(`Socket ${socket.id} connected.`);
}
Is not working at all.
I've also tested with .pem files, with ca.crt or without that... but nothing changes.

nodejs and SSL: how to specify the SSL in http.createServer creation?

I have found that snippet that works fine:
var ssl = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem')
};
var httpsServer = https.createServer(ssl).listen(port);
However my site uses that server construction:
var server = http.createServer(httpRequestsHandler).listen(_port_, function() {
process.setgid('www-data');
process.setuid('user1');
});
Question: how/where do I specify the ssl in this case ?
Based on the documentation your code has to look like this:
const https = require('https');
const fs = require('fs');
var ssl = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem')
};
var server = https.createServer(ssl, httpRequestsHandler).listen(_port_, function() {
process.setgid('www-data');
process.setuid('user1');
});
I recommend that you look at this site

Create Websocket Secure on a HTTPS web server in express app

I have a application in express.js. Am unable to create wss on a HTTPS web server.
var fs = require('fs');
var express = require('express');
var app = express();
var cfg = {
ssl: true,
port: 8001,
ssl_key: 'sslcert/ssl.key',
ssl_cert: 'sslcert/ssl.crt'
};
var httpServ = (cfg.ssl) ? require('https') : require('http');
if (cfg.ssl) {
httpsServer = httpServ.createServer({
key: fs.readFileSync(cfg.ssl_key),
cert: fs.readFileSync(cfg.ssl_cert)
}, app)
.listen(cfg.port, function () {
console.log('Magic happening at https://Secure');
});
} else {
httpsServer = httpServ.createServer(app)
.listen(cfg.port, function () {
console.log('Magic happening at http://InSecure');
});
}
var WebSocketServer = require('websocket')
.server;
var wsServer = new WebSocketServer({
httpServer: httpsServer
});
wsServer.on('connection', function connection(ws) {
console.log('Socket Connected');
});
I'm under the impression that passing a reference of the web server to WebSocket, then WebSocket would know the port and SSL capabilities of the server. But every time I get an error in the console
WebSocket connection to 'ws://localhost:8001/?trackme=TUKOCVPAF' failed: Connection closed before receiving a handshake response
How can I create a wss://localhost:8001/?trackme=TUKOCVPAF' when creating the Websocket..??

webpack-dev-server inside express?

I´m trying to understand how to use webpack-dev-server for hot bundling and reloading and I got the following code from react-redux-universal-hot-example:
var Express = require('express');
var webpack = require('webpack');
var config = require('../src/config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = config.host || 'localhost';
var port = (Number(config.port) + 1) || 3001;
var serverOptions = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true}
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> Webpack development server listening on port %s', port);
}
});
Questions:
a) Why is this code calling var app = Express() to seutp an express server ? Isn´t it webpack-dev-server a server itself ?
b) From the webpack-dev-server I expected somthing like:
var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var fs = require("fs");
var compiler = webpack({
// configuration
});
var server = new WebpackDevServer(compiler, {
// webpack-dev-server options
}) ;
Why is react-redux-universal-hot-example doing it inside a new instance of express() ?
c) Is there any docs or tutorials of this type of webpack-dev-server usage ?
Thanks for helping - I´m confused here.
As far as you see your application require a pair of middlewares
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
It's just easier to set it up having express middleware system.
There is a good documentation with examples https://webpack.github.io/docs/webpack-dev-server.html

TypeError: dest.end is not a function

I am trying to use HTTP/2. My express version is 5.0.0-alpha.2, http2 version is 3.3.4.
I suppose http2 should work well with express 5.
const http2 = require('http2');
// const http2 = require('spdy'); // using spdy package here, everything works perfect
const options = {
key: fs.readFileSync(path.join(__dirname, 'private', 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'private', 'server.crt'))
};
const server = http2
.createServer(options, app)
.listen(3000, err => {
if (err) throw new Error(err);
// I can see "Listening..." message, which means the server starts running well.
console.log('Listening...');
});
The server starts running well, but when I open client website, it gives me this error in the terminal:
_stream_readable.js:512
dest.end();
^
TypeError: dest.end is not a function
at Stream.onend (_stream_readable.js:512:10)
at Stream.g (events.js:286:16)
at emitNone (events.js:91:20)
at Stream.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
It seems node-http2 has not been supported by Express yet.
Please track this issue Support for module http on github.
In the meanwhile, you can stay with node-spdy.
const spdy = require('spdy');
const options = {
key: fs.readFileSync(path.join(__dirname, 'private', 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'private', 'server.crt'))
};
const server = spdy
.createServer(options, app)
.listen(3000, err => {
if (err) throw new Error(err);
console.log('Listening...');
});
With Express 5.0 we have another solution :
express = require( 'express' ), //Web framework
// Solution
express.request.__proto__ = http2.IncomingMessage.prototype;
express.response.__proto__ = http2.ServerResponse.prototype;
// Create app for server http/2
var apph2 = express();
And this is the server code :
var
application_root = __dirname,
express = require( 'express' ), //Web framework
http2 = require('http2')
logger = require('morgan')
fs = require('fs')
constants = require('constants');
// Bunyan logger
var bunyan = require('bunyan');
var app = require('./apps/app_name');
var bunlog = bunyan.createLogger({name: "brqx_app"});
var credentials = {
// log : bunlog ,
key : fs.readFileSync('/etc/letsencrypt/live/domain/privkey.pem' ),
cert : fs.readFileSync('/etc/letsencrypt/live/domain/fullchain.pem' ),
ca : fs.readFileSync("/etc/letsencrypt/live/domain/chain.pem" ),
dhparam : fs.readFileSync("/etc/letsencrypt/archive/domain/dh1.pem" ),
secureOptions: constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_SSLv2
};
// Configure server
server = http2.createServer( credentials , app);
server.listen(PORT , function () {
console.log('Started Brqx http/2!');
} )
I hope these easy lines helps to people.
One thing is important when we search information on Internet is the date of test when code was tested : 2017 - October.
Regards.
Ricardo/Brqx.

Resources