Skip to main content
Node.js Basics
CHAPTER 32 Beginner

Bonus: NPM & Express Cheat Sheet

Updated: May 13, 2026
10 min read

# NPM & Express Cheat Sheet

Keep this page bookmarked! This cheat sheet contains the most common commands and syntax structures you will use daily as a Node.js Backend Developer.

---

1. NPM Commands (Terminal)

Initialize a new project:

bash
1
npm init -y

Install production packages:

bash
123456
# General
npm install express mongoose dotenv
# Auth
npm install bcryptjs jsonwebtoken
# Security & Uploads
npm install helmet cors express-rate-limit multer

Install development tools:

bash
1
npm install nodemon --save-dev

Uninstall a package:

bash
1
npm uninstall <package-name>

---

2. Express Server Skeleton

The standard app.js file structure:

javascript
12345678910111213141516171819202122232425262728
// 1. Imports
require(&#039;dotenv&#039;).config();
const express = require(&#039;express&#039;);
const mongoose = require(&#039;mongoose&#039;);

const app = express();

// 2. Global Middleware
app.use(express.json()); // Parse JSON body
app.use(express.urlencoded({ extended: true })); // Parse HTML forms

// 3. Database Connection
mongoose.connect(process.env.MONGO_URI)
    .then(() => console.log(&#039;DB Connected&#039;))
    .catch(err => console.error(err));

// 4. Routes
app.get(&#039;/&#039;, (req, res) => res.send(&#039;API Running&#039;));
app.use(&#039;/api/users&#039;, require(&#039;./routes/userRoutes&#039;));

// 5. Global Error Handler
app.use((err, req, res, next) => {
    res.status(err.status || 500).json({ error: err.message });
});

// 6. Start Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Running on ${PORT}`));

---

3. Express Routing & Data Extraction

Extracting Data from Requests:

javascript
12345678910111213
app.post(&#039;/users/:id&#039;, (req, res) => {
    // 1. URL Parameters (e.g., /users/5)
    const userId = req.params.id;
    
    // 2. Query Strings (e.g., /users/5?sort=asc)
    const sortMethod = req.query.sort;
    
    // 3. JSON/Form Body (e.g., { "name": "John" })
    const name = req.body.name;
    
    // 4. Headers (e.g., Authorization: Bearer token123)
    const token = req.header(&#039;Authorization&#039;);
});

Common Response Methods:

javascript
1234567891011121314151617
// Send plain text or HTML
res.send(&#039;Hello World&#039;);

// Send JSON data (Standard for REST APIs)
res.json({ success: true, data: myObject });

// Send Status Code AND JSON
res.status(404).json({ error: "Not Found" });

// Send a File (e.g., PDF or HTML page)
res.sendFile(__dirname + &#039;/public/index.html&#039;);

// Render an EJS template
res.render(&#039;profile&#039;, { user: userData });

// Redirect to another route
res.redirect(&#039;/login&#039;);

---

4. Mongoose & MongoDB

Define a Schema & Model:

javascript
123456789
const mongoose = require(&#039;mongoose&#039;);

const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, unique: true },
    age: { type: Number, default: 18 }
}, { timestamps: true });

module.exports = mongoose.model(&#039;User&#039;, userSchema);

Common CRUD Queries:

javascript
123456789101112131415161718192021
// CREATE
const newUser = await User.create({ name: &#039;John&#039;, email: &#039;j@j.com&#039; });

// READ ALL
const users = await User.find();

// READ FILTERED
const adults = await User.find({ age: { $gte: 18 } }).sort({ name: 1 });

// READ BY ID
const user = await User.findById(req.params.id);

// UPDATE
const updatedUser = await User.findByIdAndUpdate(
    req.params.id, 
    { name: &#039;Johnny&#039; }, 
    { new: true } // Returns the updated document
);

// DELETE
await User.findByIdAndDelete(req.params.id);

---

5. Security Snippets

Hash a Password (bcryptjs):

javascript
1234
const bcrypt = require(&#039;bcryptjs&#039;);

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);

Verify a Password:

javascript
12
const isMatch = await bcrypt.compare(req.body.password, user.password);
if (!isMatch) return res.status(400).json({ error: "Invalid password" });

Generate JWT Token:

javascript
1234567
const jwt = require(&#039;jsonwebtoken&#039;);

const token = jwt.sign(
    { userId: user._id }, 
    process.env.JWT_SECRET, 
    { expiresIn: &#039;1d&#039; }
);

Custom Auth Middleware:

javascript
12345678910111213
const verifyToken = (req, res, next) => {
    const authHeader = req.header(&#039;Authorization&#039;);
    if (!authHeader) return res.status(401).json({ error: "No token" });
    
    const token = authHeader.split(&#039; &#039;)[1]; // Remove "Bearer "
    
    try {
        req.user = jwt.verify(token, process.env.JWT_SECRET);
        next();
    } catch (err) {
        res.status(400).json({ error: "Invalid token" });
    }
};

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·