Protocols
HTTP/2 Support
HTTP/2 with multiplexing and header compression, served by the native engine on the same port as HTTP/1.1. Server push and stream prioritization are available on the Node.js HTTP/2 server.
Overview
Without HTTP/2, you're missing multiplexing and header compression. With MoroJS, one option turns it on: the native engine negotiates HTTP/2 and keeps serving HTTP/1.1 on the same port, and your routes, middleware and handlers do not change.
Without HTTP/2
- One request at a time per connection
- No multiplexing
- No header compression
- Slower page loads
With MoroJS
- Served by the native engine
- Automatic multiplexing
- HPACK header compression
- HTTP/1.1 on the same port
Faster
Served by the native engine, not a separate server
Efficient
Multiplexing and header compression reduce latency
Compatible
Automatic HTTP/1.1 fallback for all clients
How It Works
With http2 enabled and the default engine, the native engine serves HTTP/2 itself (@morojs/engine 1.1.19 or later): h2 is negotiated by ALPN on a TLS listener and by prior knowledge on a cleartext one, and HTTP/1.1 clients are served on the same port. app.engine reports what booted.
1app.engine;
2// { server: 'engine', enginePackage: '@morojs/engine',
3// engineVersion: '1.1.20', protocols: ['h2', 'http/1.1'] }The server built on Node.js's http2 module is still there. It serves HTTP/2 with an older engine, with server.engine: 'node', and wherever the native engine cannot be used (app.engine.server is then 'http2'). Routes, middleware and handlers are the same on both.
Not available over HTTP/2 on the native engine
- Server push: res.push() exists and returns null, as it does on the Node.js server for a client that has turned push off
- Stream prioritization: res.setPriority() is only defined on the Node.js HTTP/2 server
- WebSocket over HTTP/2 (RFC 8441); WebSocket upgrades over HTTP/1.1 on the same port are unaffected
- req.httpVersion is set by the Node.js servers only; read app.engine.protocols to see what the engine's listener speaks
- To keep the Node.js HTTP/2 server, set server.engine: 'node'
Quick Start
1import { createApp } from '@morojs/moro';
2import * as fs from 'fs';
3
4const app = await createApp({
5 http2: true,
6 https: {
7 key: fs.readFileSync('key.pem'),
8 cert: fs.readFileSync('cert.pem'),
9 },
10});
11
12app.get('/', (req, res) => {
13 res.json({ message: 'Hello HTTP/2!' });
14});
15
16app.listen(3000);1const app = await createApp({
2 http2: {
3 allowHTTP1: true, // Support HTTP/1.1 fallback
4 settings: {
5 maxConcurrentStreams: 100,
6 initialWindowSize: 65535,
7 maxFrameSize: 16384,
8 },
9 },
10 https: {
11 key: fs.readFileSync('key.pem'),
12 cert: fs.readFileSync('cert.pem'),
13 },
14});
15
16// settings.enablePush is accepted but never sent: RFC 9113 forbids a
17// server from advertising it. Whether push is possible is the client's
18// setting, read per stream.1// server.ssl takes the same material as https (either shape). With file
2// paths, watch: true reloads the certificate when the files change on disk
3// (an ACME renewal, a rotated Kubernetes secret) - validated first, so a
4// half-written file never replaces the certificate that is serving.
5const app = await createApp({
6 http2: true,
7 server: {
8 ssl: {
9 keyFile: '/etc/tls/server.key',
10 certFile: '/etc/tls/server.crt',
11 watch: true, // or { debounceMs: 1000 }
12 },
13 },
14});
15
16// Or rotate explicitly: re-read the files, or hand over new material.
17// Connections already established are untouched.
18await app.reloadTLS();
19await app.reloadTLS({ keyFile: '/etc/tls/new.key', certFile: '/etc/tls/new.crt' });
20
21// Works on the native engine (@morojs/engine 1.1.8+), the Node https
22// server and the Node HTTP/2 server.Server Push
Server push needs two things: the Node.js HTTP/2 server (server.engine: 'node'), and a client that allows push. Push is switched on by the client's SETTINGS_ENABLE_PUSH, which MoroJS reads per stream; res.push() returns null when it is off. Chrome and Firefox have disabled push, so expect null from browsers and rely on <link rel="preload"> there.
1import { middleware } from '@morojs/moro';
2
3app.use(middleware.http2Push({
4 autoDetect: true, // Auto-detect CSS/JS from HTML
5 resources: [
6 {
7 path: '/styles/main.css',
8 as: 'style',
9 type: 'text/css',
10 priority: 200 // High priority
11 },
12 {
13 path: '/scripts/app.js',
14 as: 'script',
15 type: 'application/javascript',
16 priority: 150
17 },
18 ],
19 condition: (req) => req.path === '/' || req.path.endsWith('.html'),
20}));1app.get('/', (req, res) => {
2 // Check if push is available
3 if (res.push) {
4 // Push CSS with high priority
5 const cssStream = res.push('/styles/main.css', {
6 headers: { 'content-type': 'text/css' },
7 priority: 200,
8 });
9
10 if (cssStream) {
11 cssStream.end('body { font-family: Arial; }');
12 }
13
14 // Push JavaScript
15 res.push('/scripts/app.js', {
16 headers: { 'content-type': 'application/javascript' },
17 priority: 150,
18 });
19 }
20
21 res.send('<html>...</html>');
22});Stream Prioritization
res.setPriority() is defined on the Node.js HTTP/2 server (server.engine: 'node'). Guard the call, as below, and the same handler runs on the native engine.
1// Critical API endpoint - highest priority
2app.get('/api/critical', (req, res) => {
3 if (res.setPriority) {
4 res.setPriority({
5 weight: 256, // 1-256, higher = more important
6 exclusive: true // Exclusively process this stream
7 });
8 }
9
10 res.json({ critical: 'data' });
11});
12
13// Background data - low priority
14app.get('/api/background', (req, res) => {
15 if (res.setPriority) {
16 res.setPriority({ weight: 1 });
17 }
18
19 res.json({ background: 'data' });
20});1// Priority weight ranges from 1-256:
2// 256 - Critical resources (HTML, critical API data)
3// 200 - High priority (CSS, fonts)
4// 150 - Medium priority (JavaScript)
5// 100 - Normal priority (images)
6// 50 - Low priority (analytics, tracking)
7// 1 - Lowest priority (background tasks)SSL Certificates
1# Generate self-signed certificate
2openssl req -x509 -newkey rsa:2048 -nodes -sha256 \
3 -subj '/CN=localhost' \
4 -keyout localhost-key.pem \
5 -out localhost-cert.pem
6
7# For production, use certificates from a trusted CA like Let's EncryptChecking HTTP Version
1// On the Node.js servers (engine: 'node'), per request
2app.get('/', (req, res) => {
3 const httpVersion = req.httpVersion; // '2.0' or '1.1'
4
5 if (httpVersion === '2.0') {
6 // Use HTTP/2 features
7 res.push('/assets/critical.css');
8 }
9
10 res.json({ version: httpVersion });
11});
12
13// On any server: what the listener speaks
14app.engine.protocols; // ['h2', 'http/1.1']Best Practices
1. Use Server Push Wisely
Only push resources that are:
- • Critical for initial render
- • Small in size (< 100KB)
- • Used by most users
2. Set Appropriate Priorities
1// Critical path
2res.setPriority({ weight: 256, exclusive: true });
3
4// Important but not critical
5res.setPriority({ weight: 200 });
6
7// Background/analytics
8res.setPriority({ weight: 1 });3. Enable HTTP/1.1 Fallback
1const app = await createApp({
2 http2: {
3 allowHTTP1: true, // Clients without HTTP/2 support
4 },
5 https: { /* ... */ },
6});Features
Core Features
- HTTP/2 served by the native engine
- ALPN h2 over TLS, prior knowledge over cleartext
- Multiplexing (multiple requests over single connection)
- HPACK header compression
- HTTP/1.1 on the same port
- Server push and stream prioritization on the Node.js HTTP/2 server
Benefits
- No separate server to run or configure
- Reduced latency with multiplexing
- Better resource prioritization
- Improved bandwidth utilization
- Backward compatible with HTTP/1.1