Skip to content

šŸ’” This Simple Express.js Trick Will Blow Your Mind

Tips to write cleaner and faster Express code like a seasoned pro!


šŸ¤” Think Express.js is Simple? Think Again.

Express is simple—but mastering it means knowing those clever little tricks that make your code ✨ clean, fast, and beautiful. This post isn’t about building routes… it’s about writing smarter Express apps.


šŸš€ The Trick: Use express.Router() for Clean, Modular Routing

Instead of dumping all routes in index.js like this:





// index.js
app.get('/users', getUsers);
app.post('/users', createUser);
app.put('/users/:id', updateUser);

Split your code like a pro:

āœ… Create a router module

routes/userRoutes.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => res.send('Get users'));
router.post('/', (req, res) => res.send('Create user'));
router.put('/:id', (req, res) => res.send('Update user'));

module.exports = router;

āœ… Use it in your main app

index.js

const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');

app.use('/api/users', userRoutes);

Boom! Cleaner, reusable, and maintainable.


šŸ” Bonus Tip 1: Use asyncHandler to Catch Errors Automatically

Avoid writing try/catch in every route.

🧠 Problem:

router.get('/', async (req, res) => {
  try {
    const users = await getUsers();
    res.json(users);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

šŸš€ Solution: Use a wrapper!

npm install express-async-handler
const asyncHandler = require('express-async-handler');

router.get('/', asyncHandler(async (req, res) => {
  const users = await getUsers();
  res.json(users);
}));

No try/catch, no clutter. šŸ’„


🧼 Bonus Tip 2: Use Middleware Like a Pro

Instead of writing auth logic in every route…

āŒ Don’t do this:

router.get('/dashboard', (req, res) => {
  if (!req.user) return res.status(401).send('Unauthorized');
  res.send('Welcome!');
});

āœ… Do this:

middleware/auth.js

module.exports = (req, res, next) => {
  if (!req.headers.authorization) return res.status(401).send('Unauthorized');
  // Add your token logic here
  next();
};

Apply it globally or per-route

const auth = require('./middleware/auth');
app.use('/api/secure', auth, secureRoutes);

āš™ļø Bonus Tip 3: Use res.locals for Shared Data

Need to pass user info across middleware and routes?

app.use((req, res, next) => {
  res.locals.user = { id: 1, name: 'Devesh' };
  next();
});

app.get('/dashboard', (req, res) => {
  res.send(`Welcome, ${res.locals.user.name}`);
});

Great for templating and context sharing.


šŸŽÆ TL;DR

TrickWhy it rocks
express.Router()Cleaner file structure
express-async-handlerAvoids messy try/catch
MiddlewareDRY and secure code
res.localsShare data without global vars

Leave a Reply

Your email address will not be published. Required fields are marked *