DEV Community

Cover image for Node.js HTTP server without any frameworks.
Gian felipe theodorowicz
Gian felipe theodorowicz

Posted on

Node.js HTTP server without any frameworks.

Ok, so to create an API using Node.Js, first, it's necessary to install Express as dependency and then... Wait, we actually need 'Express' to build an http server in Node.Js?

Node.Js might needs external frameworks to build an API? see above.

What is HTTP

HTTP is a transfer protocol that enables people to... wait, let's go straight to the point, HTTP is text-based, no connection basically means people who access a site x, send requests to a server x that returns to who ordered, images, texts, and other media, after the request is answered, the connection between who ordered and who responded, is cut off.

Usually when we deal with HTTP requests in general, we guide ourselves with something, basically when something makes a request for a server, it expects an answer, but an answer is something very broad, so the famous status-codes were created, now we stop get guiding only by data and now we get guiding by number codes as well, But wait, where did the data go? Calm they are still sent by the server to whom you requested them, but now they are present within the request's content, the 'body'.

Now that I introduced to what is HTTP protocol, and clarified how it works, let's write and get out of the world of ideas and enter the world of codes, where there is no right or wrong, just what works and does not work... You may be wondering how my computer will send a request from my home to a server on the other side of the country or even the mainland, and I'll still get back an answer... Calm down, these and other headaches are already solved by modern technologies present both in programming languages natively, and even within browsers such as Firefox, Google, Opera, etc. Since we don't have to worry about the way these requests will be made, we will then start thinking uniquely and exclusively about our code. For this, we will use Node.js 19.8.1.

We should start questioning, how to create an API?

Probably, you when I asked, instantly aswered happy and smilling, that's easy!

fisrt we instantiate the Express using:

import express from 'express';
const app = express();
Enter fullscreen mode Exit fullscreen mode

or by fastify:

import fastify from 'fastify';
const app = fastify()
Enter fullscreen mode Exit fullscreen mode

... I say we couldn't limit ourselves only by using frameworks, justly by the fact they are built by something, that's why they are called, frameworks.

But after all, what precisely is this 'something'?

I can't answer with such certainty by what frameworks like 'express' or 'fastify' are built. But, natively, inside Node.js we have a way to build an HTTP server, that's inside the module 'http' or 'node:http'. Particuly this module have a native function, createServer, so to answer the question above mentioned...

// we started by calling inside Node.js the module 'node:http', and extracting the 'createServer'
import { createServer } from 'node:http'

// after, we instantiate it inside a constant, by any name.
const app = createServer() 
Enter fullscreen mode Exit fullscreen mode

This way, by theory, we already have a server receiving HTTP, but we will a little deeper:

import { createServer } from 'node:http'

// the function createServer, by default receive a property 'requestHandler', so we create a function and pass it as property
async function HttpHandler(
  request, response
){}

const app = createServer(httpHandler)
Enter fullscreen mode Exit fullscreen mode

Now looks more beauty, right? well, we have an HTTP server that is receiving HTTP requests, and we are handling the requests... But what if I say that isn't working yet? yes, the createServer function have to be called with some arguments... we have the .listen(port) argument that is passed to the createServer can listen and send request on some network port.

import { createServer } from 'node:http'


async function HttpHandler(request, response){}

const app = createServer(HttpHandler)
.listen(3333)
.on('listening', () => console.log('http server ready'))
Enter fullscreen mode Exit fullscreen mode

Notice that I add one more thing beyond .listen(), and to understand exactly what is this .on(), we might know what is events in Node.js, but don't worry, I will make a summary suitable to this article.

Events are notifications that can be handled by calling a function that emits these notifications, and that's notifications should have some data and headers inside, so we can consume them!

Now that you already know something about events, will should notice that the .on() is an event, and their headers or flag, is 'listening', so we handle it and order console.log() to notice it on our terminal.

Good right? we have our own HTTP server that is listening and aswering!

wait... you ran the code and isn't working with you? yes... I forgot to wrote a return haha!

import { createServer } from 'node:http'

async function HttpHandler(request, response){
  try {
    const data = request
    response.writeHead(200)
  } catch (e) {
    response.writeHead(500)
  }
}

const app = createServer(HttpHandler)
.listen(3333)
.on('listening', () => console.log('http server ready'))
Enter fullscreen mode Exit fullscreen mode

Notice that now, I am really interacting with HTTP requests, in truth, I am litering returning differents status for whom requested, based on the state of my code, but we have a little problem when we use const data = requests, justly by the request is the result of an event, i.e, inside of my createServer, what is an event emmiter, not all events are requests, so to resolve it, we can use a solution provided by Node.js as well:

import { createServer } from 'node:http'

import { once } from 'node:events'

async function HttpHandler(request, response){
  try { 
    // now we are handle just when we have request data!
    const data = await once(request, 'data')
    response.writeHead(200)
  } catch (e) {
    response.writeHead(500)
  }
}

const app = createServer(HttpHandler)
.listen(3333)
.on('listening', () => console.log('http server ready'))
Enter fullscreen mode Exit fullscreen mode

See how easy building an HTTP server in Node.js without any framework can be? But I would let highlight those frameworks help us to build applications faster, but I believe that we should know what we are doing before using any framework, I hope you liked it.

Top comments (1)

Collapse
 
giancarlozucoloto profile image
giancarlozucoloto

Top!