Topics in this subject
Node.js 2 min read Updated 11 Aug 2026

Node.js & Express Cheat Sheet

Quick reference for common Node.js and Express snippets.

🧑‍🏫 Sabse pehle — simple mein samjho#

Ye ek quick reference page hai jab tum backend server setup kar rahe ho. Ise bookmark karke rakho!

1. Basic Server Setup#

const express = require('express');
const app = express();

app.use(express.json()); // Parse JSON bodies

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

2. Standard Route Types#

// GET - Read
app.get('/api/users', (req, res) => {
    res.json([{ name: "Tarun" }]);
});

// POST - Create
app.post('/api/users', (req, res) => {
    const data = req.body; // Depends on express.json()
    res.status(201).json(data);
});

// PUT / PATCH - Update (Requires ID param)
app.put('/api/users/:id', (req, res) => {
    const { id } = req.params;
    res.json({ message: `Updated user ${id}` });
});

3. File System (Promises)#

const fs = require('fs/promises');

// Read
const data = await fs.readFile('config.json', 'utf-8');

// Write
await fs.writeFile('config.json', JSON.stringify({ key: "value" }));

4. Middleware Template#

const myMiddleware = (req, res, next) => {
    console.log(req.method);
    
    // Auth Check Example
    if (!req.headers.authorization) {
        return res.status(401).json({ error: "Missing token" });
    }
    
    next(); // IMPORTANT: Pass to next function
};

// Apply to all routes
app.use(myMiddleware);

// Apply to specific route
app.get('/protected', myMiddleware, (req, res) => res.send('Secret'));

5. Async Route Wrapper (Avoid Try-Catch Everywhere)#

(Alternative to using express-async-errors package)

const asyncHandler = (fn) => (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);
};

app.get('/data', asyncHandler(async (req, res) => {
    const data = await db.query(); // Will auto-catch and pass to global handler
    res.json(data);
}));

6. Global Error Handler#

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(err.status || 500).json({
        success: false,
        message: err.message || "Server Error"
    });
});

7. JWT Verification Snippet#

const jwt = require('jsonwebtoken');

// Sign
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' });

// Verify
const decoded = jwt.verify(token, process.env.JWT_SECRET);