DEV Community

Cover image for Building a Simple REST API with Express.js — The Right Way
Kafeel Ahmad
Kafeel Ahmad

Posted on

Building a Simple REST API with Express.js — The Right Way

Most Node.js developers start with Express when learning backend development. But even experienced devs often overlook key architectural decisions that impact scalability, maintainability, and security.

Today, we'll walk through building a clean, modular REST API using Express.js, covering:

  • API structure
  • Routing
  • Controllers
  • Middlewares
  • Error handling
  • Environment configs

🧱 Project Structure

Start with a clean structure:

project-root/
├── controllers/
├── routes/
├── middlewares/
├── models/
├── config/
├── utils/
├── app.js
└── server.js

This modular setup scales well for growing apps.

🧪 Step-by-Step: Create a Simple API

1. Install Express

npm init -y
npm install express dotenv

2. Create server.js

const app = require('./app');
const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

3. Create app.js

const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');

app.use(express.json());
app.use('/api/users', userRoutes);
// Global error handler
app.use((err, req, res, next) => {
  res.status(err.status || 500).json({ message: err.message });
});
module.exports = app;

4. Add a Controller (controllers/userController.js)

exports.getAllUsers = (req, res) => {
  res.json([{ id: 1, name: 'Dipak' }]);
};

5. Add a Route (routes/userRoutes.js)

const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');

router.get('/', userController.getAllUsers);
module.exports = router;

🛡️ Add Environment Config

  • Create .env file:
PORT=5000
NODE_ENV=development
  • Install dotenv:
npm install dotenv
  • Load it in server.js:
require('dotenv').config();

🔒 Add Error Handling Middleware

In middlewares/errorHandler.js:

const errorHandler = (err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Something went wrong!' });
};

module.exports = errorHandler;

And in app.js:

const errorHandler = require('./middlewares/errorHandler');
app.use(errorHandler);

📦 Bonus: Add CORS & Helmet for Security

npm install cors helmet
const cors = require('cors');
const helmet = require('helmet');

app.use(cors());
app.use(helmet());

✅ Final Output

Once set up, run your server:

node server.js

Visit: http://localhost:5000/api/users

You'll get:

[
  { "id": 1, "name": "Dipak" }
]

Clean, modular, and production-ready!

🔚 Final Thoughts

Building REST APIs in Node.js is simple — but doing it right requires planning.

Start clean, modularize your logic, and build secure endpoints. You're not just learning Express — you're becoming a better backend engineer.

Author: Dipak Ahirav

Top comments (0)