🌐Web Development

Express.js

Express

A Node.js web framework. Minimalist design. Middleware-based architecture.

πŸ“–Detailed Explanation

Express.js is the de facto standard web framework for Node.js, released in 2010. It records more than 30 million weekly downloads on npm, and about 70% of Node.js backends use Express. With its minimal and flexible design, you can combine various middleware to build the functionality you want.

The core concept is the middleware chain. It processes requests (req) and responses (res) sequentially, and passes control to the next middleware with the next() function. Common logic such as logging, authentication, CORS, and error handling can be separated into middleware and reused.

Express 4.x has long been maintained as the stable version, while 5.x is in the alpha stage. Thanks to its large ecosystem, middleware exists for almost every feature, including passport (authentication), multer (file upload), helmet (security), and cors. Higher-level frameworks such as NestJS and Feathers are also built on Express.

As drawbacks, TypeScript support is not native, asynchronous error handling is cumbersome, and performance is lower than that of later frameworks such as Fastify. However, thanks to its overwhelming ecosystem and references, it is still the most widely used option.

πŸ’»Code Example

// Express.js 미듀웨어 기반 API μ„œλ²„
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';

const app = express();

// κΈ€λ‘œλ²Œ 미듀웨어
app.use(helmet()); // λ³΄μ•ˆ 헀더
app.use(cors({ origin: 'https://myapp.com' }));
app.use(express.json()); // JSON νŒŒμ‹±

// μ»€μŠ€ν…€ λ‘œκΉ… 미듀웨어
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);
  next();
});

// 인증 미듀웨어
const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) {
    return res.status(401).json({ error: 'Token required' });
  }
  try {
    req.user = verifyToken(token);
    next();
  } catch {
    res.status(403).json({ error: 'Invalid token' });
  }
};

// 라우트 μ •μ˜
app.get('/api/public', (req, res) => {
  res.json({ message: 'Public data' });
});

app.get('/api/protected', authMiddleware, (req, res) => {
  res.json({ user: req.user, message: 'Protected data' });
});

// 비동기 라우트 (Express 4.xμ—μ„œλŠ” try-catch ν•„μš”)
app.get('/api/users/:id', async (req, res, next) => {
  try {
    const user = await db.users.findById(req.params.id);
    if (!user) return res.status(404).json({ error: 'Not found' });
    res.json(user);
  } catch (error) {
    next(error); // μ—λŸ¬ λ―Έλ“€μ›¨μ–΄λ‘œ 전달
  }
});

// μ—λŸ¬ 처리 미듀웨어 (4개 인자 ν•„μˆ˜)
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Internal server error' });
});

app.listen(3000, () => console.log('Server running on :3000'));

πŸ—£οΈHow It's Said in Practice

πŸ’ΌAt a Project Kickoff

"We're planning to go with Express for the backend. Most of the team members have Express experience, and all the middleware we need is available, so we can build an MVP quickly. If performance becomes critical, it won't be too late to consider migrating to Fastify then."

🎯In a Technical Interview

"Interviewer: Please explain the execution order of Express middleware.

Candidate: They run in the order they were registered with app.use(). Each middleware must call next() for execution to move on to the next middleware, and if next() is not called, the chain stops. Error middleware takes 4 arguments, and when next(error) is called, it skips the regular middleware and goes to the error middleware."

πŸ”In a Code Review

"You're using await in an async route handler without try-catch, but Express 4.x doesn't automatically catch promise rejections. Use the express-async-errors package, or wrap every async handler in try-catch."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️Cautions

πŸ”—Related Terms

πŸ“šLearn More