Skip to main content
Node.js APIs Tutorial
CHAPTER 05 Beginner

Creating Your First Node.js Server

Updated: May 14, 2026
25 min read

# CHAPTER 5

Creating Your First Node.js Server

1. Introduction

When you build a website with HTML, you rely on software like Apache or Nginx to act as the web server. Node.js is different. In Node.js, *you write the web server yourself*. Using the built-in http module, we can instruct our computer to listen for incoming internet traffic, process it, and send a response back. In this chapter, we will build a pure Node.js web server from scratch.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the built-in http module to create a server.
  • Understand the req (Request) and res (Response) objects.
  • Send an HTTP status code and response headers.
  • Listen on a specific network port.

3. Beginner-Friendly Explanation

Imagine you are starting a drive-thru restaurant. You need three things:
  1. 1. The Building (The Server): You need a physical place to do business.
  1. 2. The Speakerbox (The Port): You need a specific frequency where customers can talk to you.
  1. 3. The Cashier (The Callback Function): When a customer talks into the speaker (a Request), the cashier figures out what they want, and hands them food (the Response).

In Node.js, we write a few lines of code to create the building, assign the speakerbox to Port 3000, and write a function that hands back data to anyone who visits http://localhost:3000.

4. Step 1: Importing the HTTP Module

Node.js comes with several core modules out of the box. You do not need to npm install them. The http module contains all the networking logic required to build a server.

Create a file named server.js and add:

javascript
12
// Import the built-in module
const http = require('http');

5. Step 2: Creating the Server

We use the createServer method. It takes a callback function with two critical arguments:
  • req: The incoming Request (what the user asked for).
  • res: The outgoing Response (what we will send back).
javascript
12345678
const server = http.createServer((req, res) => {
    
    // 1. Tell the browser "Success (200)" and "I am sending you plain text"
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    
    // 2. Send the actual data and end the connection
    res.end('Welcome to my Node.js Server!');
});

6. Step 3: Listening on a Port

The server exists in memory, but it isn't listening for traffic yet. A computer has thousands of "Ports" (doors). Web traffic usually enters through Port 80 or 443. For local development, we typically use Port 3000, 5000, or 8080.
javascript
123456
const PORT = 3000;

// Tell the server to listen on door 3000
server.listen(PORT, () => {
    console.log(`Server is running and listening on port ${PORT}`);
});

7. The Complete Code

Here is your complete server.js file:
javascript
123456789101112131415161718192021
const http = require('http');

const server = http.createServer((req, res) => {
    // Basic routing logic
    if (req.url === '/') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Home Page');
    } else if (req.url === '/api/users') {
        // Returning JSON instead of text
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ name: 'John Doe', role: 'Admin' }));
    } else {
        // 404 Error
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 - Page Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running on port 3000');
});

To run this: Open your terminal and type node server.js. Then visit http://localhost:3000/api/users in your browser.

8. Backend Workflow: Why Pure Node.js is Painful

Look at the code above. To handle just two URLs, we had to write messy if/else statements. If we had 100 APIs, our code would be 1,000 lines of if/else spaghetti. Furthermore, extracting JSON data from a POST request in pure Node.js requires reading complex data streams manually. This is why professional developers almost *never* use the raw http module to build full applications. We use frameworks.

9. Best Practices

  • Never Hardcode Ports: In production, companies like Heroku or AWS assign random ports dynamically. You should always use environment variables. const PORT = process.env.PORT || 3000;. This says: "Use the server's requested port, but if we are on my local laptop, use 3000."

10. Common Mistakes

  • Forgetting res.end(): If you forget to call res.end() inside your server block, the server will accept the request but never finish responding. The user's web browser will show a spinning loading wheel forever until it eventually times out.

11. Exercises

  1. 1. Explain the roles of the req (Request) and res (Response) objects in the http.createServer callback function.

12. Coding Challenges

  • Challenge: Modify the server.js file to add a new route: /about. If a user visits /about, return an HTML string: <h1>About Us</h1>. Make sure to change the Content-Type header to text/html.

13. MCQs with Answers

Question 1

Which built-in Node.js module is required to create a web server?

Question 2

What happens if you forget to include res.end() in your server response logic?

14. Interview Questions

  • Q: Explain the purpose of process.env.PORT when defining a server's listening port.
  • Q: Why do developers rarely use the raw http module to build large-scale REST APIs? What specific challenges arise?

15. FAQs

Q: Can I run multiple Node.js servers on my laptop at the same time? A: Yes, as long as they are assigned to different ports. You can have one API running on Port 3000, and a different API running on Port 4000. If you try to run both on 3000, Node will throw an EADDRINUSE (Address already in use) error.

16. Summary

In Chapter 5, we became server engineers. By utilizing Node's built-in http module, we established a listener on Port 3000. We intercepted incoming requests (req), manipulated the HTTP Headers to specify our data format (Plain text or JSON), and finalized the connection using res.end(). However, we also identified the limitations and messy routing logic required when using pure Node.js.

17. Next Chapter Recommendation

To fix the messy if/else routing of pure Node.js, we need a framework. Proceed to Chapter 6: Introduction to Express.js, the industry standard tool for building APIs.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·