What is the NPM package?

Npm (Node Package Manager) is libraries or modules written in javascript. NPM allow us to share and reuse a piece of code through the Node js ecosystem.

In this blog we gonna walkthrough widely using NPM packages in a nutshell. Play around with these packages based on your requirements.

Widely using npm packages in express JS project

ExpressJS

Express js itself is a standalone npm package. It’s a lightweight framework for creating faster, scalable web applications.


npm install express
const express = require('express');
const app = express();
app.use(express.json());  
app.get('/', (req, res) => {
  res.send('Hello World!');
});
const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Body-parser

Body-parser enables us to ****parse the request body and extract data from the backend.

npm install body-parser
const bodyParser = require('body-parser');

// Middleware to parse JSON request body
app.use(bodyParser.json());
app.post('/api/data', (req, res) => {
  const data = req.body; // Access parsed request body
  res.json({ message: 'Data received', data });
});

Morgan

It’s a middleware function that enables the log of the HTTP request information.

npm install morgan
const morgan = require('morgan');

// Middleware for logging HTTP requests
app.use(morgan('dev'));

app.get('/api/users', (req, res) => {
  res.json({ message: 'List of users' });
});
// HTTP request information in console
GET /api/users 200 10.899 ms - 45
const cors = require('cors');

// Middleware for enabling CORS
app.use(cors());

For the sake of simplicity, we use passport-local here.


const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

// Configure Passport with a local authentication strategy
passport.use(new LocalStrategy(
  function(username, password, done) {

    // Code to check if the username and password are valid
    if (username === 'admin' && password === 'password') {

      return done(null, { id: 1, username: 'admin' });
    } else {

      return done(null, false);
    }
  }
));

// Initialize Passport and restore authentication state, if any, from the session
app.use(passport.initialize());
app.use(passport.session());

In package.json file

"scripts": {
  "start": "node app.js",
  "dev": "nodemon app.js"
}

Dotenv

Dotenv enables you to get process sensitive information without explicitly showing the credentials through the app.

npm install dotenv
const dotenv = require('dotenv');

dotenv.config(); // Load environment variables from .env file

// Access environment variables
const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASSWORD;
console.log(`Database User: ${dbUser}`);

Mongoose

Mongoose is a MongoDB object modelling tool for express js.

npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('MongoDB connected');
}).catch(err => {
  console.error('MongoDB connection error:', err);
});

Express-Validator

Express-validator is a middleware for validating and sanitizing user input in Express.js applications.

npm install express-validator
const { body, validationResult } = require('express-validator');
app.post('/user', [
  body('email').isEmail().withMessage('Invalid email address'),
  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // Handle valid input
});

Conclusion

This is a comprehensive list of npm packages that are widely used in Express.js applications. Each package serves a specific purpose, from handling requests and responses to managing databases and validating user input. By incorporating these packages into your Express.js projects, you can enhance functionality, improve security, and streamline development processes. Feel free to explore each package further and adapt them to your specific project needs.

Happy coding! 😊