DEV Community

rabindratamang
rabindratamang

Posted on • Edited on

Mastering ESLint for Node.js: Tips and Tricks to Write Cleaner Code

Writing clean, maintainable, and bug-free Node.js applications isn't just about experience—it’s about using the right tools. ESLint is like your personal code assistant, catching errors early, enforcing coding standards, and making sure your code stays readable. But are you using it to its full potential? In this post, I’ll share some practical ESLint tips and tricks tailored for Node.js development, packed with examples based on ESLint v8.x.


Why ESLint Matters for Node.js

Node.js apps often juggle asynchronous operations, database interactions, and API requests. Without proper linting, small mistakes can snowball into major headaches. ESLint helps by:

  • Catching syntax errors before runtime.
  • Enforcing consistent coding styles across your team.
  • Identifying issues like unused variables and improper error handling.

Now, let’s get into some actionable tips to boost your ESLint game.


1. Use the Right ESLint Config for Node.js

The right configuration can save you hours of frustration. Instead of starting from scratch, use a solid preset like eslint-config-airbnb-base or eslint-config-standard. These come with sensible defaults for Node.js.

Setting up eslint-config-airbnb-base

npm install eslint eslint-config-airbnb-base --save-dev
Enter fullscreen mode Exit fullscreen mode

Then, update your .eslintrc.js:

module.exports = {
  extends: 'airbnb-base',
  env: {
    node: true, // Enable Node.js global variables
    es2021: true, // Use modern ECMAScript features
  },
  rules: {
    // Customize rules here
  },
};
Enter fullscreen mode Exit fullscreen mode

Boom! You now have best practices baked into your setup.


2. Enable ES Modules Support

If you’re using ES Modules (ESM) in your project, make sure ESLint is on the same page. Add this to .eslintrc.js:

module.exports = {
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
};
Enter fullscreen mode Exit fullscreen mode

Now ESLint won’t complain when you use modern imports:

import fs from 'fs';

export function readFile(path) {
  return fs.promises.readFile(path, 'utf-8');
}
Enter fullscreen mode Exit fullscreen mode

3. Catch Common Node.js Errors

Unhandled Promises

Forgetting to handle a rejected promise can crash your app. The no-unused-vars rule can help catch this.

Bad:

async function fetchData() {
  const data = await fetch('https://api.example.com');
}
Enter fullscreen mode Exit fullscreen mode

Good:

async function fetchData() {
  try {
    const data = await fetch('https://api.example.com');
    return await data.json();
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Other useful rules:

  • no-callback-literal: Ensures callbacks are used correctly.
  • no-unused-vars: Prevents memory leaks.

4. Enforce Consistent Error Handling

Error handling is critical in Node.js apps. Make sure you:

  • Always wrap async calls in try-catch.
  • Use no-throw-literal to ensure only Error objects are thrown.

Bad:

throw 'Something went wrong';
Enter fullscreen mode Exit fullscreen mode

Good:

throw new Error('Something went wrong');
Enter fullscreen mode Exit fullscreen mode

5. Optimize for Performance

Performance matters. ESLint can help you avoid blocking the event loop.

  • Avoid sync methods with no-sync:

Bad:

const data = fs.readFileSync('file.txt', 'utf8');
Enter fullscreen mode Exit fullscreen mode

Good:

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode
  • Prevent memory leaks by catching unused variables.

6. Enforce Security Best Practices

Security should be non-negotiable. Use these ESLint rules to stay safe:

  • no-eval: Prevents executing arbitrary code.
  • eslint-plugin-security: Catches common vulnerabilities.
  • no-process-env: Warns against hardcoded credentials.

Bad:

const dbPassword = 'mypassword';
Enter fullscreen mode Exit fullscreen mode

Good:

const dbPassword = process.env.DB_PASSWORD;
Enter fullscreen mode Exit fullscreen mode

7. Customize Rules for Your Team

Every team has its own coding standards. ESLint lets you tailor rules:

  • Force camelCase naming with camelcase.
  • Limit function complexity with complexity.

Example: Keeping Functions Simple

Bad: Too much nesting!

function processData(data) {
  if (data) {
    if (data.items) {
      for (let i = 0; i < data.items.length; i++) {
        if (data.items[i].status === 'active') {
          console.log('Processing:', data.items[i]);
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Good: Break it into smaller functions.

function processItem(item) {
  if (item.status === 'active') {
    console.log('Processing:', item);
  }
}

function processData(data) {
  if (data?.items) {
    data.items.forEach(processItem);
  }
}
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

ESLint is more than just a linter—it’s your personal code assistant. By fine-tuning its rules, you can:
✅ Catch errors early
✅ Write cleaner code
✅ Improve performance & security

Try out these tips, tweak ESLint for your project, and let me know what works best for you! Happy coding!

Top comments (0)