DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to Write Clean and Maintainable Code in MERN

Writing clean and maintainable code is essential for building scalable and efficient applications, especially in the MERN (MongoDB, Express.js, React, Node.js) stack. Following best practices not only makes your code easier to read and understand but also improves collaboration and long-term maintainability. Here’s how you can achieve that:


1. Follow a Consistent Coding Style

A consistent coding style improves readability and reduces cognitive load when reviewing or debugging code.

  • Use ESLint and Prettier to enforce style rules.
  • Follow naming conventions (camelCase for variables and functions, PascalCase for React components).
  • Keep indentation, spacing, and line breaks consistent.

Example .eslintrc.json setup:

{
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "rules": {
    "indent": ["error", 2],
    "quotes": ["error", "single"],
    "semi": ["error", "always"]
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Modularize Your Code

Break your code into smaller, reusable functions and components to improve readability and reusability.

Backend (Node.js & Express.js)

Instead of writing everything in server.js, split concerns into different files.

Bad Example:

app.get('/users', (req, res) => {
  const users = db.find();
  res.json(users);
});
Enter fullscreen mode Exit fullscreen mode

Good Example: (Using a controller)

// controllers/userController.js
exports.getUsers = (req, res) => {
  const users = db.find();
  res.json(users);
};
Enter fullscreen mode Exit fullscreen mode
// routes/userRoutes.js
const express = require('express');
const { getUsers } = require('../controllers/userController');
const router = express.Router();
router.get('/users', getUsers);
module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Frontend (React.js)

Use reusable components instead of duplicating code.

Bad Example:

function UserCard(props) {
  return (
    <div>
      <h3>{props.name}</h3>
      <p>{props.email}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Good Example: (Using destructuring and separate styles)

function UserCard({ name, email }) {
  return (
    <div className="user-card">
      <h3>{name}</h3>
      <p>{email}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. Use Meaningful Variable and Function Names

Poor naming can make code difficult to understand. Choose clear, descriptive names.

Bad Example:

const x = getData();
Enter fullscreen mode Exit fullscreen mode

Good Example:

const userList = fetchUserList();
Enter fullscreen mode Exit fullscreen mode

4. Keep Functions Short and Focused

Each function should perform a single task.

Bad Example:

function processUserData(user) {
  const fullName = `${user.firstName} ${user.lastName}`;
  console.log(fullName);
  db.save(user);
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

function getFullName(user) {
  return `${user.firstName} ${user.lastName}`;
}

function saveUser(user) {
  db.save(user);
}
Enter fullscreen mode Exit fullscreen mode

5. Handle Errors Properly

Ignoring errors can cause unexpected failures. Always handle them gracefully.

Bad Example:

const user = getUser(id);
console.log(user.name);
Enter fullscreen mode Exit fullscreen mode

Good Example:

try {
  const user = getUser(id);
  console.log(user.name);
} catch (error) {
  console.error("Failed to fetch user:", error.message);
}
Enter fullscreen mode Exit fullscreen mode

6. Use Environment Variables

Never hardcode sensitive information.

Bad Example:

const dbPassword = "mysecretpassword";
Enter fullscreen mode Exit fullscreen mode

Good Example: (Using .env file)

DB_PASSWORD=mysecretpassword
Enter fullscreen mode Exit fullscreen mode
require('dotenv').config();
const dbPassword = process.env.DB_PASSWORD;
Enter fullscreen mode Exit fullscreen mode

7. Write Unit and Integration Tests

Testing ensures your application works as expected and prevents future bugs.

  • Use Jest for unit testing.
  • Use Supertest for API testing in Express.js.

Example test using Jest:

test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

Example API test:

const request = require('supertest');
const app = require('../server');

test('GET /users returns a list of users', async () => {
  const response = await request(app).get('/users');
  expect(response.statusCode).toBe(200);
  expect(response.body).toBeInstanceOf(Array);
});
Enter fullscreen mode Exit fullscreen mode

8. Optimize Performance

  • Use lazy loading in React to improve load time.
  • Implement pagination for large datasets.
  • Use indexes in MongoDB for efficient querying.

Example of pagination in Express.js:

app.get('/users', async (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const users = await db.find()
    .skip((page - 1) * limit)
    .limit(parseInt(limit));
  res.json(users);
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these best practices, you can write clean, maintainable, and scalable MERN applications. Always aim for simplicity, reusability, and clarity in your code. Start implementing these tips today, and your future self (and teammates) will thank you! 🚀

Support My Work ❤️

If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!

Connect with Me 🌍

Let’s stay connected! You can follow me or reach out on these platforms:

🔹 YouTube – Tutorials, insights & tech content

🔹 LinkedIn – Professional updates & networking

🔹 GitHub – My open-source projects & contributions

🔹 Instagram – Behind-the-scenes & personal updates

🔹 X (formerly Twitter) – Quick thoughts & tech discussions

I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!

Disclaimer

This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →