Building a web server with pure Node.js
Tags: javascript, node, webdev
Published: 2019-11-02 18:54:09

There are many frameworks for Node.js to build a web server application. I am adding several of the most well-known ones below.
* [Express](https://expressjs.com)
* [Koa](https://koajs.com)
* [hapi.js](https://hapijs.com)

However, what if we don’t want to use any of them? We can build a web server by using pure Node.js. Of course, these frameworks make our life easier. Personally, I often use Express framework mostly but I will use pure Node.js API from now on as much as possible, especially for small projects :) This is simply because of the fact that these frameworks add many dependencies to our project so it causes huge __node_modules__.

![node_modules becomes really huge in projects if you use many frameworks and libraries
](https://miro.medium.com/proxy/1*tLmdca91O3WXf_ZTiy8JFA.jpeg)
A simple web application or server can be built equally easily by using built-in modules making our apps more lightweight and easy to manage/maintain.
If you are used to reading code better than words, here’s a simple web server application built without any frameworks on Node.js. [You can also check on GitHub from this link](https://github.com/hcoz/pure-nodejs-web-server).

```
const http = require('http');
/** handle GET request */
function getHandler(req, res, reqUrl) {
  res.writeHead(200);
  res.write('GET parameters: ' + reqUrl.searchParams);
  res.end();
}

/** handle POST request */
function postHandler(req, res, reqUrl) {
  req.setEncoding('utf8');
  req.on('data', (chunk) => {
    res.writeHead(200);
    res.write('POST parameters: ' + chunk);
    res.end();
  });
}

/** if there is no related function which handles the request, then show error message */
function noResponse(req, res) {
  res.writeHead(404);
  res.write('Sorry, but we have no response..\n');
  res.end();
}

http.createServer((req, res) => {
  // create an object for all redirection options
  const router = {
    'GET/retrieve-data': getHandler,
    'POST/send-data': postHandler,
    'default': noResponse
  };
  // parse the url by using WHATWG URL API
  let reqUrl = new URL(req.url, 'http://127.0.0.1/');
  // find the related function by searching "method + pathname" and run it
  let redirectedFunc = router[req.method + reqUrl.pathname] || router['default'];
  redirectedFunc(req, res, reqUrl);
}).listen(8080, () => {
  console.log('Server is running at http://127.0.0.1:8080/');
});
```

Firstly, I am creating an HTTP server by using `createServer()` method from the HTTP API of Node.js. In the request listener part of it, I am detecting the request and redirecting the related function.

As you can see, I have three functions which are `getHandler()`, `postHandler()` and `noResponse()`. They are handling the related URL request. URL and function couples are stored in `router` object as `{ method/url: function }`.

Then, I parse the URL by using the [WHATWG URL API](https://nodejs.org/api/url.html#url_the_whatwg_url_api). One of the reasons for this, I can get many URL functionalities such as pathname, host, origin, etc and I can handle easily without struggling string manipulations. After that, I construct my request key which is `req.method + reqUrl.pathname` for searching related function.

And finally, find the related function from `router` and call it by passing `request` and `response` objects. If there is no related function in the object then I call the default one which is `noResponse()` in our case.

Here is my approach to creating a simple web server with pure Node.js. In my opinion, working on a software language without any framework is also important to understand the basics of it.

You can read this [MDN documentation](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Node_server_without_framework) for an extended example of a pure Node.js server. And of course, [Node.js API](https://nodejs.org/api/) is the most important document which helps you!

Additionally, you can check the [server-side of my NLP Command Line App project](https://github.com/hcoz/sem-cli-server) for a more detailed implementation of the pure Node.js server. Also, read [my article about this project](https://dev.to/halilcanozcelik/an-nlp-command-line-application-with-node-js-33na) if you want to learn more about it.

My some other articles:
[Create a Multi-Language Website with React Context API](https://dev.to/halilcanozcelik/create-a-multi-language-website-with-react-context-api-4i27)
[Chrome Devtool Tips](https://dev.to/halilcanozcelik/chrome-devtool-tips-2eb)
[An NLP Command Line Application with Node.js](https://dev.to/halilcanozcelik/an-nlp-command-line-application-with-node-js-33na)