DEV Community

Cover image for Node.js Best Practices: A Guide for Developers
Mehedi Hasan
Mehedi Hasan

Posted on

Node.js Best Practices: A Guide for Developers

Nodejs is a powerful tool for building fast and scalable web applications. However, to get most out to nodejs it is important to follow best practices. In this blog post, we will explore some key best practices for nodejs development.

1. Structure Your Project

A well-structured project is easy to maintain and scale. Here's a simple structure that you can follow:

my-node-app/
│
├── src/
│   ├── controllers/
│   ├── models/
│   ├── routes/
│   └── services/
│
├── tests/
│
├── .env
├── .gitignore
├── package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • src/ contains your main application code.
    • controllers/ handle the logic for your app.
    • models/ define your data structures.
    • routes/ manage the different endpoints of your API.
    • services/ contain business logic.
  • tests/ contain all the test files.
  • .env stores your environment variables
  • .gitignore specifies files to ignore in GIT.
  • .package.json keeps track of dependencies and scripts.
  • README.md describes your project.

2. Use Environment Variables

Environment variables help keep your configuration settings outside your code. This makes your app more secure and easier to manage.

Example:
Create a .env file:

DB_HOST=localhost
DB_USER=root
DB_PASS=password
Enter fullscreen mode Exit fullscreen mode

Load these variables in your code using the dotenv package:

require('dotenv').config();

const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASS;

console.log(`Connecting to database at ${dbHost} with user ${dbUser}`);
Enter fullscreen mode Exit fullscreen mode

3. Handle Errors Properly

Handling error properly ensures that your app doesn't crash unexpectedly.

app.get('/user/:id', async (req, res, next) => {
  try {
    const user = await getUserById(req.params.id);
    if (!user) {
      return res.status(404).send('User not found');
    }
    res.send(user);
  } catch (error) {
    next(error);
  }
});

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});
Enter fullscreen mode Exit fullscreen mode

4. Use Asynchronous Code

Nodejs is asynchronous by nature. Use async and await to handle asynchronous code more cleanly.

Example:

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

fetchData();
Enter fullscreen mode Exit fullscreen mode

5. Keep Dependencies Updated

Regularly update your dependencies to ensure you have latest features and security fixes.

Use npm outdated to check for outdated packages.

npm outdated
Enter fullscreen mode Exit fullscreen mode

Update packages:

npm update
Enter fullscreen mode Exit fullscreen mode

6. Write Tests

Testing your code helps catch bug early and ensures that your app works
as expected.

Example:
Step 1: Install Jest

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

Step 2: Write tests
Create test file, for example, tests/example.test.js. Here's a simple example to get you started.

const sum = (a, b) => a + b;

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

7. Use A Linter

Linters help you write clean and consistent code. ESLint is a popular choice.

Example:

Install ESLint:

npm install eslint --save-dev
Enter fullscreen mode Exit fullscreen mode

Initialize ESLint:

npx eslint --init
Enter fullscreen mode Exit fullscreen mode

Add a lint script to your package.json:

"scripts": {
  "lint": "eslint ."
}
Enter fullscreen mode Exit fullscreen mode

Run the linter:

npm run lint
Enter fullscreen mode Exit fullscreen mode

Conclusion

Following these best practices will help you write better, more maintainable nodejs application. Remember to structure your project, use environmental variables, handle errors properly, write asynchronous code, keep dependencies updated, write tests and use a linter. By doing so, you will create robust and efficient nodejs applications that are easier to manage and maintain.

Happy Coding!

Top comments (33)

Collapse
 
saikumar2121 profile image
Saikumar

Adding logging to a Node.js application is essential for gaining insights and troubleshooting issues effectively. By following best practices in logging, developers can ensure they capture real problems and improve the overall reliability and performance of the application.

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

You are absolutely right. Adding logging is another key best practice. Thank you for this.

Collapse
 
gandanje profile image
Gilbert Andanje • Edited

This is awesome! A little spoiler. The same way we have create-react-app for frontend there is this framework for backend called suite that follows this structure. Suite helps you scaffold a project with suite generate command with the initial server listening at port 9001. You may try it out with npm install @microservices-suite/cli -g. Or checkit out here npmjs.com/package/@microservices-s...

Collapse
 
otumianempire profile image
Michael Otu

Error handling is key just as logging was suggested. From the snippet on error handling I'd suggest that the error not me hidden ... Handle each error gracefully.. it would be best when one implements different error cases.. not found, forbidden, unauthorized or token or jwt expire errors, etc,

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

yeah your are right implementing different error cases is good practice too. I just wanted to keep things simple here. Thanks for mentioning it

Collapse
 
jyoung4242 profile image
Justin Young

NGL, i wish i read this three years ago when i started developing with JS

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan • Edited

Glad to share @jyoung4242

Collapse
 
hazemgharib profile image
Hazem Gharib

Great tips!

I would also add few more like:

  • using proper authentication
  • using TypeScript
  • including linting in pre-commit
  • add a CI/CD pipeline (e.g. GitHub actions)
Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

Yeah these are good tips too. Thank you for sharing

Collapse
 
litlyx profile image
Antonio | CEO at Litlyx.com

For all Javascript framework we have created the simpliest KPI tracker, with just one-lince code of setup. We are even opensource, give it a try.

Open-Source Git Repo -- Leave a ✨ if you like!

A. CEO & Founder at Litlyx

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

Hey Antonio I will check it later

Collapse
 
litlyx profile image
Antonio | CEO at Litlyx.com

I would love it for real! Thanks my man, keep up the goo work!

Collapse
 
devpaul3000 profile image
Dev Paul

Love the tips. Thanks man

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

Welcome

Collapse
 
m_idrees555 profile image
MUHAMMAD IDREES • Edited

Excellent 👌👍, May Allah Bless You.
I'll try to follow these tips, bcz I'm interested in Back-End Development.

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

May Allah bless you too and best of luck on your back-end journey.

Collapse
 
m_idrees555 profile image
MUHAMMAD IDREES

Are you a Back-End developer? Please guide me from start to market/industry...!

Collapse
 
tharcissentirandekura profile image
Ntirandekura Tharcisse

I am a beginner in nodejs and yours advice really helps and now I know how to set up my project dev environment cleanly. Thanks very much

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

My pleasure. @tharcissentirandekura

Collapse
 
sharmi2020 profile image
Sharmila kannan

Nice article

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan • Edited

Hi @sharmi2020 , Thank your very much for your feedback