DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Building a Simple Node.js Server with Express

If you’re getting started with backend development or API design, Node.js is one of the best places to begin. It’s lightweight, fast, and powered by JavaScript — meaning you can use one language across both frontend and backend.

In this short guide, we’ll set up a simple Node.js server using the popular Express framework.


Step 1: Initialize Your Project

Create a new folder for your project and open it in your terminal:

mkdir simple-node-server
cd simple-node-server
Enter fullscreen mode Exit fullscreen mode

Initialize Node.js:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This command creates a package.json file to manage your project dependencies.


⚙️ Step 2: Install Express

Express is a minimalist web framework that makes building APIs much easier.

Install it using:

npm install express
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Server File

Create a file named server.js and paste the following code:

// server.js
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to parse JSON requests
app.use(express.json());

// Default route
app.get('/', (req, res) => {
  res.send('Hello from Node.js server 👋');
});

// Sample POST route
app.post('/api/data', (req, res) => {
  const { name } = req.body;
  res.json({ message: `Hello ${name}, your data was received successfully!` });
});

// Start the server
app.listen(PORT, () => {
  console.log(`🚀 Server running at http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Server

Start your server by running:

node server.js
Enter fullscreen mode Exit fullscreen mode

You’ll see this message in your terminal:

Server running at http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

Now open your browser and visit:

👉 http://localhost:3000

You should see:

Hello from Node.js server 👋
Enter fullscreen mode Exit fullscreen mode

Step 5: (Optional) Try a POST Request

You can test your /api/data route using Postman, Insomnia, or cURL:

curl -X POST http://localhost:3000/api/data -H "Content-Type: application/json" -d '{"name":"Sospeter"}'
Enter fullscreen mode Exit fullscreen mode

Expected response:

{
  "message": "Hello Sospeter, your data was received successfully!"
}
Enter fullscreen mode Exit fullscreen mode

✅ Conclusion

And that’s it — your first Node.js server!
From here, you can expand it with:

  • JWT authentication
  • Database connections (MongoDB, PostgreSQL, MySQL)
  • API routes for user registration, payments, etc.
  • Environment variables for secure configuration

With Node.js and Express, you have the foundation to build anything from a small API to a full-scale backend service.

Top comments (0)