5 ways to create an HTTP/HTTP2 server with Node.js.

Node.js can be used to easily run a web server by using the built-in HTTP module or a web framework such as Express, Hapi, or Fastify. The process involves creating an HTTP server, setting up routes, and starting the server to listen on a specific port for incoming requests.

1. Using the built-in http.createServer

The easiest and most typical way is to use the built-in http module.

const http = require('http')
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('Hello World\n')
})
server.listen(3000, '127.0.0.1')
console.log('Server running at http://127.0.0.1:3000/')

Here we create a non-secure server on port 3000, and provide a default handler for all requests.

2. Using the Express package

Express is a popular package for all things servers. You can find many useful packages to handle any case in Express. Of course, you will need to install it from NPM with npm install express

const express = require('express')
const app = express()
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(3000, () => console.log('Example app listening on port 3000!'))

3. Using the Hapi package

Hapi is another popular package to consider. Hapi is a web and application framework for building web applications and services in Node.js. It offers a rich set of features for building robust and scalable applications. Install it from NPM with npm install hapi.

const Hapi = require('hapi');
const server = Hapi.server({
    host:'localhost',
    port: 3000
});
server.route({
    method: 'GET',
    path: '/',
    handler: (request, h) => {
        return 'Hello World!';
    }
});
const start = async () => {
    try {
        await server.start();
    }
    catch (err) {
        console.log(err);
        process.exit(1);
    }
    console.log('Server running at:', server.info.uri);
};
start();

In general, Hapi is a popular framework known for its flexibility and extensibility. It provides a lot of functionality out of the box, and a lot of plugins to use, which will save you a lot of time and effort when building your web application.

4. Using the Fastify package

Fastify is a web framework for Node.js designed to be fast and low-overhead. It is built on top of the popular Node.js HTTP library, and provides a simple and easy-to-use API for building web applications and services.

const fastify = require('fastify')();
fastify.get('/', (req, res) => {
  res.send('Hello World!');
});
fastify.listen({ port: 3000 }).then((address) => {
  console.log(`Server running at ${address}`);
}).catch(e => {
  console.log(`Error! ${e.message}`);
});

5. Using the built-in http2.createServer (available from Node 8.4.0)

Starting from Node 8.4.0, we can use the HTTP2 package, which provides us with the necessary functionality to run an HTTP2 server.

const fs = require('fs');
const http2 = require('http2');
const options = {
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
};
const port = 3001;
const server = http2.createServer(options, (req, res) => {
  console.log('requested');
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});
server.listen(port, '127.0.0.1');
console.log(`Server running at http://127.0.0.1:${port}/`);

HTTP/2 is a newer version of the HTTP protocol that is designed to improve performance and reduce latency. It is fully backwards-compatible with HTTP/1.1, which means that if a client supports HTTP/2, it can still communicate with a server that supports only HTTP/1.1, and vice versa.

When a client that supports HTTP/2 connects to a server that only supports HTTP/1.1, the client will automatically “fall back” to using HTTP/1.1. This means that any client, regardless of whether it supports HTTP/2 or not, will be able to communicate with a server that supports HTTP/2.

You will need to have a private key and a certificate to be able to run an HTTP2 server. For development purposes, you can create an SSL/TLS key with the openssl command-line tool, and generate a self-signed certificate. Here is an example command for “localhost”:

openssl req -x509 -out localhost-cert.pem -keyout localhost-privkey.pem \
  -newkey rsa:2048 -nodes -sha256 \
  -subj '/CN=localhost' -extensions EXT -config <( \
   printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

Please note that self-signed certificates are not trusted by default and browser will show warnings to the user. In production environment, you will need to use a trusted certificate issued by a certificate authority (CA).


Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *