ALPN negotiation allows supporting both [HTTPS][] and HTTP/2 over the same socket. The req and res objects can be either HTTP/1 or HTTP/2, and an application must restrict itself to the public API of [HTTP/1][], and detect if it is possible to use the more advanced features of HTTP/2.

    The following example creates a server that supports both protocols:

    1. const { createSecureServer } = require('http2');
    2. const { readFileSync } = require('fs');
    3. const cert = readFileSync('./cert.pem');
    4. const key = readFileSync('./key.pem');
    5. const server = createSecureServer(
    6. { cert, key, allowHTTP1: true },
    7. onRequest
    8. ).listen(4443);
    9. function onRequest(req, res) {
    10. // Detects if it is a HTTPS request or HTTP/2
    11. const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?
    12. req.stream.session : req;
    13. res.writeHead(200, { 'content-type': 'application/json' });
    14. res.end(JSON.stringify({
    15. alpnProtocol,
    16. httpVersion: req.httpVersion
    17. }));
    18. }

    The 'request' event works identically on both [HTTPS][] and HTTP/2.