If you’re stepping into the world of Node.js, one of the first tasks you’ll encounter is creating a simple Node.js server. The concept might sound complicated, but it’s surprisingly simple. In this blog, you’ll learn how to build your very first Node.js server step-by-step. By the end, you’ll have a fully functional server running on your computer.
What is a Node.js Server?
A Node.js server is a simple, lightweight, and efficient server that can handle incoming requests and send back responses. Instead of relying on web servers like Apache or Nginx, Node.js allows you to create your own server from scratch. This is especially useful for creating APIs, web apps, or real-time applications like chats or live feeds.
With Node.js, you can use JavaScript (the same language used in browsers) to run server-side applications. This means you can use a single language for both the client (browser) and the server.
Prerequisites
Before creating a Node.js server, make sure you have the following tools ready:
- Node.js installed on your machine. Download Node.js.
- A text editor like Visual Studio Code.
- Basic knowledge of JavaScript.
To check if Node.js is installed, run the following command in your terminal:
node -v
If it returns a version number (e.g., v18.0.0
), you’re good to go.
Step 1: Create a New Project
Start by creating a folder for your project.
- Create a new folder for your project:
mkdir my-first-node-server
cd my-first-node-server
2 . Initialize the project with a package.json
file:
npm init -y
This creates a package.json
file that tracks your dependencies and project metadata. You’re now ready to write your first Node.js server.
Step 2: Write Your First Node.js Server
Here comes the exciting part — building the server.
- Create a file named
server.js
in your project folder. - Open
server.js
and paste the following code:
// Import the HTTP module (a built-in Node.js module)
const http = require('http');
// Set the hostname and port for the server
const hostname = '127.0.0.1'; // Localhost (your computer)
const port = 3000; // Port number (can be any unused port)
// Create the server
const server = http.createServer((req, res) => {
// Set the status code and content type
res.statusCode = 200; // OK status
res.setHeader('Content-Type', 'text/plain'); // Plain text content
// Send the response to the browser
res.end('Hello, World!\nWelcome to my first Node.js server!');
});
// Start the server and listen on the specified port
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Code Breakdown
http.createServer()
: Creates a new server.req
(request) andres
(response) represent the incoming request and the server’s response.res.end()
: Sends a response back to the browser.server.listen()
: Starts the server and makes it listen for requests on the specified port.
Step 3: Start Your Node.js Server
Run the following command to start the server:
node server.js
If everything works correctly, you’ll see this message in the terminal:
Server running at http://127.0.0.1:3000/
Step 4: View the Server in Your Browser
- Open your web browser.
- Go to http://127.0.0.1:3000/ or http://localhost:3000/.
- You should see this message on the page:
Hello, World!
Welcome to my first Node.js server!
Congratulations! Your first Node.js server is up and running.
Customizing Your Server
Now that you have a basic server, let’s customize it.
1- Dynamic Routes
Right now, your server only responds to one URL (/
). Let’s add different routes for different pages.
Update server.js
with the following code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html'); // HTML instead of plain text
if (req.url === '/') {
res.end('<h1>Welcome to the Home Page</h1>');
} else if (req.url === '/about') {
res.end('<h1>About Us</h1><p>This is the about page.</p>');
} else if (req.url === '/contact') {
res.end('<h1>Contact Us</h1><p>Contact us at email@example.com</p>');
} else {
res.statusCode = 404;
res.end('<h1>404 - Page Not Found</h1>');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Test these routes:
- http://localhost:3000/ — Home Page
- http://localhost:3000/about — About Us Page
- http://localhost:3000/contact — Contact Us Page
- http://localhost:3000/anything-else — 404 Page Not Found
2- Serving Static Files
You can serve static files (like images, CSS, and JavaScript) using fs (file system).
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.statusCode = 500;
res.end('Error loading the file.');
} else {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(data);
}
});
} else {
res.statusCode = 404;
res.end('404 Not Found');
}
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server is running at http://127.0.0.1:3000/');
});
Put an index.html file in the same directory as server.js.
Why Create Your Own Server?
- Full Control: You have full control of how to handle requests, responses, and errors.
- API Development: You can create APIs to send and receive JSON data.
- Server-Side Apps: Build interactive, real-time applications like chat apps, dashboards, and more.
Common Issues
Q1: Address already in use
- Solution: Use a different port (change
port = 3000
to something likeport = 4000
).
Q2: 404 Not Found
- Solution: Make sure you’re visiting the correct route, like /about instead of /about.html.
Conclusion
Congratulations! You’ve just built your first Node.js server. You now know how to:
- Set up a server.
- Handle routes and requests.
- Serve static files.
- Customize content dynamically.
This knowledge is the foundation for building modern web apps, REST APIs, and real-time services. You can now move on to frameworks like Express.js for a more powerful server experience.
If you have any questions or need further guidance, feel free to ask. Happy coding! 🚀
Comments