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

Not a Member? Read for FREE here.

🧱 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.

<a rel="noopener follow" href="https://blog.stackademic.com/can-you-optimize-node-js-streams-for-maximum-performance-c4e690bcf051">


            <h2>Can You Optimize Node.js Streams for Maximum Performance?</h2>

                <h3>Mastering Node.js streams: the secret to handling massive data efficiently without crashing your app.</h3>
Enter fullscreen mode Exit fullscreen mode
            <div class="mt-5">
                <p class="text-xs text-grey-darker">stackademic.com</p>
            </div>
        </div>
        <div class="relative flex h-40 flew-row w-60">
            <div class="absolute inset-0 bg-center bg-cover" style="background-image: url('https://miro.medium.com/v2/resize:fit:320/1*oOFYAyqNJmqqcwnI7-1Irw.png'); background-repeat: no-repeat;" referrerpolicy="no-referrer"></div>
        </div>
    </div>
</a>

Connect with Me

If you enjoyed this post and would like to stay updated with more content like this, feel free to connect with me on social media:

Email: Email me on dipaksahirav@gmail.com for any questions, collaborations, or just to say hi!

I appreciate your support and look forward to connecting with you!

A message from our Founder

Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community.

Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don't receive any funding, we do this to support the community. ❤️

If you want to show some love, please take a moment to follow me on LinkedIn, TikTok, Instagram. You can also subscribe to our weekly newsletter.

And before you go, don't forget to clap and follow the writer️!

Author: Dipak Ahirav

Top comments (0)