Middleware
Middleware
Performs processing between request and response. Used for authentication, logging, and error handling.
Middleware
Performs processing between request and response. Used for authentication, logging, and error handling.
Middleware is a function that runs between the request and the response in a web application. It handles common logic before a client's request reaches the final handler (router, controller), or performs post-processing before the response is sent to the client. This reduces code duplication and separates concerns.
Typical use cases for middleware include authentication/authorization, request logging, setting CORS headers, parsing request bodies, and error handling. In Express.js, you register middleware with app.use() and pass control to the next middleware by calling the next() function.
The order of execution matters in middleware. Middleware runs in the order it is registered, so authentication middleware must be registered before the protected routes. Error-handling middleware is registered after all other middleware to handle global errors. Understanding the middleware chain concept lets you build complex request-processing pipelines.
Modern frameworks each provide their own middleware patterns. Next.js supports middleware that runs on the Edge Runtime through the middleware.ts file, and Koa provides an elegant async/await-based middleware model. These middleware patterns are the web version of AOP (aspect-oriented programming) and handle cross-cutting concerns effectively.
// Express.js ๋ฏธ๋ค์จ์ด ํจํด
import express, { Request, Response, NextFunction } from 'express';
const app = express();
// 1. ๋ก๊น
๋ฏธ๋ค์จ์ด - ๋ชจ๋ ์์ฒญ ๊ธฐ๋ก
const loggerMiddleware = (req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
// ์๋ต ์๋ฃ ํ ๋ก๊ทธ ๊ธฐ๋ก
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - ${res.statusCode} (${duration}ms)`);
});
next(); // ๋ค์ ๋ฏธ๋ค์จ์ด๋ก ์ ๋ฌ
};
// 2. ์ธ์ฆ ๋ฏธ๋ค์จ์ด - JWT ํ ํฐ ๊ฒ์ฆ
interface AuthRequest extends Request {
user?: { id: string; email: string; role: string };
}
const authMiddleware = async (req: AuthRequest, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = verifyToken(token); // JWT ๊ฒ์ฆ ํจ์
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
// 3. ๊ถํ ํ์ธ ๋ฏธ๋ค์จ์ด - ์ญํ ๊ธฐ๋ฐ ์ ๊ทผ ์ ์ด
const requireRole = (...roles: string[]) => {
return (req: AuthRequest, res: Response, next: NextFunction) => {
if (!req.user) {
return res.status(401).json({ error: 'Authentication required' });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
};
// 4. ์๋ฌ ํธ๋ค๋ง ๋ฏธ๋ค์จ์ด (4๊ฐ์ ์ธ์)
const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
console.error('Error:', err.stack);
if (err.name === 'ValidationError') {
return res.status(400).json({ error: err.message });
}
if (err.name === 'UnauthorizedError') {
return res.status(401).json({ error: 'Invalid token' });
}
res.status(500).json({ error: 'Internal server error' });
};
// ๋ฏธ๋ค์จ์ด ๋ฑ๋ก (์์ ์ค์!)
app.use(express.json()); // ์์ฒญ ๋ณธ๋ฌธ ํ์ฑ
app.use(loggerMiddleware); // ๋ชจ๋ ์์ฒญ ๋ก๊น
// ๊ณต๊ฐ ๋ผ์ฐํธ
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// ์ธ์ฆ ํ์ ๋ผ์ฐํธ
app.get('/api/profile', authMiddleware, (req: AuthRequest, res) => {
res.json({ user: req.user });
});
// ๊ด๋ฆฌ์ ์ ์ฉ ๋ผ์ฐํธ
app.delete('/api/users/:id',
authMiddleware,
requireRole('admin'),
(req, res) => {
res.json({ message: 'User deleted' });
}
);
// ์๋ฌ ํธ๋ค๋ฌ๋ ๊ฐ์ฅ ๋ง์ง๋ง์ ๋ฑ๋ก
app.use(errorHandler);
// === Next.js Middleware (Edge Runtime) ===
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// ์ธ์ฆ ํ์ธ
const token = request.cookies.get('auth-token');
// ๋ณดํธ๋ ๊ฒฝ๋ก ์ฒดํฌ
if (pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// ์๋ต ํค๋ ์ถ๊ฐ
const response = NextResponse.next();
response.headers.set('x-custom-header', 'my-value');
return response;
}
// ๋ฏธ๋ค์จ์ด๊ฐ ์คํ๋ ๊ฒฝ๋ก ์ง์
export const config = {
matcher: ['/dashboard/:path*', '/api/:path*']
};
"The authentication code is duplicated in every API. It looks hard to maintain. How can we improve it?"
"You can separate the authentication logic into middleware. If you create an authMiddleware and apply it in front of the routes that need protection, you can apply consistent authentication without code duplication."
"Error logs are recorded differently for each API, which makes monitoring hard."
"Create a global error-handling middleware and handle all errors in one place. If you register an error handler that takes four arguments at the very end of the middleware chain, it can catch every error without try-catch and log them in a consistent format."
"What happens if middleware doesn't call next()?"
"The request stops and is not passed on to the next middleware or route handler. Unless you are intentionally sending a response (for example, on authentication failure), you must always call next(). Otherwise the client never receives a response and a timeout occurs."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Middleware order: Middleware runs in the order it is registered. Authentication middleware must be registered before the protected routes, and the error handler last. If the order is wrong, authentication can be bypassed or errors go unhandled.
Missing next(): If middleware does not send a response, it must call next(). If you forget, the request hangs indefinitely, and in async middleware the error handler only works if you call next(error) or throw the error when one occurs.
Performance considerations: Middleware that runs on every request directly affects performance. Apply heavy computation or external API calls only to the routes that need them, and use caching. Next.js middleware runs on the Edge Runtime, so the full Node.js API is not available.