beginner

Creating server


We are finally ready to start using NodeJS and create our webserver but before we do let’s first go through some common terms and their definitions (also available in Glossary)

server/webserver

Server is a physical computer or system. They are usually found in clusters in what are called server farms or data centers/clusters but you can also make your home PC a server if you want. Webserver is a virtual “application” that handles requests and responses and delivers web content to clients. Webserver cannot exist without a server(physical computer).

In reality, server is used to describe both but in majority of cases it is referring to a webserver.

frontend/backend

Frontend (or client-side) refers to the part of a web application that users interact with directly. This means that everything you see in your web browser is frontend in a sense. Backend (or server-side) is the part of a web application that users don’t see. It manages the behind-the-scenes functionality and data processing.

api

API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. It defines the methods and data formats that applications can use to request and exchange information. APIs are used to enable the integration of different systems, making it easier for developers to leverage functionalities from one application in another. API and backend are often used interchangeably when talking about them.

database

Database refers to any system that is used for storing data.

request/response

Request is when a client asks server some information or asks it to perform some specific action. The client can is usually frontend but can also be other backend systems or mobile applications and so on. Put simply, anything that comes TO the server is considered a request.

Response is when a server sends back an information to the client after processing a request.

Creating a Server

Begin by creating a dedicated folder for your project. Inside your project folder, initialize a new Node.js project using the following command in terminal

npm init -y

This command generates a package.json file with default values(⏭️).

Write Your Server Code

Now, let’s create the server file. Open your text editor and create a file named server.js:

// server.js

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, Node.js Server!");
});

const PORT = 3000;

server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

This code sets up a basic HTTP server that responds with “Hello, Node.js Server!” when accessed.

Run Your Server

In the terminal, run the following command to start your Node.js server:

node server.js

Visit http://localhost:3000 in your web browser, and you should see your server’s greeting!

Understanding the Code

We use Node.js’s built-in http module(⏭️) using built-function require to create a server. The createServer method takes a callback function, handling incoming requests (req) and sending responses (res)(⏭️). As you can see it is returning an object. We set the response header with a status code of 200 (OK) and a content type of plain text using built-in function writeHead. We return a response by using end function. The server listens on port 3000(commonly used for development) on localhost, and a message is logged to the console once it’s running.

Localhost

It is often used to access services that are running on the same machine where the browser is installed. When you use “localhost” as the host name in a URL, it is essentially an alias for the loopback IP address 127.0.0.1 meaning that if you type 127.0.0.1:3000 in your browser it is the same as localhost:3000.

Ports

A port is like a door through which information can flow in and out of a computer or a specific application. It is a numerical identifier used to distinguish different communication channels on a computer and it ranges from 0 to 65535. Ports allow a single device to handle multiple network services simultaneously. Different applications on the same computer can use different ports to avoid interference.

We have different types of ports:

  • Well-Known Ports (0-1023): These are reserved for common, standardized services. For example, HTTP typically uses port 80, and HTTPS uses port 443.
  • Registered Ports (1024-49151): These are used by specific applications or services but aren’t as standardized as well-known ports.
  • Dynamic or Private Ports (49152-65535): These are available for any application or service to use on a temporary basis.

Depending on which service(s) you’re using you won’t be able to use some ports but as you’ll see that won’t be an issue in our development.

Status codes

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

Informational responses (100 – 199)

Successful responses (200 – 299)

Redirection messages (300 – 399)

Client error responses (400 – 499)

Server error responses (500 – 599)

Majority of these are not commonly used and you will usually see just a few of them being used, most commonly:

  • 200 OK
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 422 Unprocessable Content
  • 429 Too Many Requests
  • 500 Internal Server Error
  • 502 Bad Gateway

In our server code we used 200 to indicate that request was handled OK and this status code will be available to client and the client can do some logic based on that response status code.

Throughout our posts we will different status codes depending on our usecase.

Headers

HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value. Whitespace before the value is ignored.

Throughout our posts we will different request and response headers depending on our usecase.

In our server code we used 'Content-Type': 'text/plain' which is a representation header that is used to indicate the original media type of the resource (prior to any content encoding applied for sending). Basically, we are telling the client what is the type of the content that we are sending in our response. The value text/plain is a string but defined as a media type, commonly known as MIME type.

What Now?

Now you have a Node server running and we will see how to handle routes in the next post.

Previous Handling errors
Next Routes