wrapper for express app to work with http2 protocol
npm install http2-express-bridgebash
$ npm install http2-express-bridge
`
Usage
`js
const express = require('express')
const http2Express = require('http2-express-bridge')
const http2 = require('http2')
const { readFileSync } = require('fs')
const app = http2Express(express)
const options = {
key: readFileSync(''),
cert: readFileSync(''),
allowHTTP1: true
};
app.get('/', function (req, res) {
res.send('Hello World')
})
const server = http2.createSecureServer(options, app)
server.listen(3000, () => {
console.log( listening on port 3000)
})
`
It will create a http2 server with all the perks of using http2 on supported browsers, but will revert back to Http1.1 on browsers that dont.
This should work out of the box without any further modification on your existing express application.
No Browser supports http2 without https connection. so the above approach is recommended. However, http2.createServer should also work, as long as https connection is used at the edges like HAProxy.
This can also be used as ESModules with 'import' syntax and Typescript (check examples folder).
Server Push
One of the most hyped advantages of http2 is server push. To make it easier, push() method is added to the response.
`js
const express = require('express')
const http2Express = require('http2-express-bridge')
const http2 = require('http2')
const path = require('path')
const { readFileSync } = require('fs')
const app = http2Express(express)
const options = {
key: readFileSync(''),
cert: readFileSync(''),
allowHTTP1: true
};
// this will create a static path from which files are served
const staticPath = path.join(__dirname, '')
app.use(express.static(staticPath))
app.get('/bar', (req, res) => {
// This accepts a single path or an array of paths. Path should be same as the ones in html below
// Second argument is the Root directory from which the files are being served
res.push(['/bar.js', '/foo.js'], staticPath)
res.send(
);
})
const server = http2.createSecureServer(options, app)
server.listen(3000, () => {
console.log(listening on port 3000)
})
``