0Pricing
Node.js Backend Development Bootcamp · 강의

사용자 정의 Express 미들웨어 개발

직접 Express 미들웨어 함수를 작성하여 기능을 확장하고 요청 처리를 간소화합니다.

사용자 정의 Express 미들웨어 개발은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is Custom Middleware?

In Express.js, middleware functions are like a chain of helpers that process incoming requests before they reach your final route handler.

  • They have access to the request (req) and response (res) objects.
  • They can modify these objects, end the request-response cycle, or pass control to the next middleware.
  • Custom middleware allows you to add specific functionality tailored to your application's needs, such as logging, authentication, or data parsing.

The Middleware Signature

Every Express middleware function follows a specific signature: (req, res, next).

  • req (request): The incoming HTTP request object.
  • res (response): The HTTP response object that Express sends back.
  • next: A function that, when called, passes control to the next middleware function in the stack. If you don't call next(), the request-response cycle stops, and no further middleware or route handlers will execute.

Your First Logger Middleware

Let's create a simple custom middleware that logs details of every incoming request to the console. This helps in debugging and monitoring.

Try running the code and then accessing http://localhost:3000 in your browser. Check the console output!

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

// Custom logging middleware
const requestLogger = (req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Pass control to the next middleware/route handler
};

// Apply the custom middleware globally
app.use(requestLogger);

// Define a simple route
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Applying Middleware: Global vs. Route

You can apply middleware at different levels:

  • Globally (Application-level): Using app.use(middlewareFunction) applies the middleware to ALL incoming requests.
  • Route-specific: You can apply middleware to specific routes or groups of routes by passing it as an argument before the route handler.

This flexibility allows you to execute logic only where it's needed.

Passing Data Downstream

A powerful feature of middleware is its ability to add properties to the req object. These properties then become accessible to all subsequent middleware functions and the final route handler in the request-response cycle.

This is extremely useful for things like attaching user information after authentication, or parsed data before reaching the main logic.

Example: Attaching User Data

Here's how you might attach a mock user object to the request. In a real application, this data would come from a database or a decoded JSON Web Token (JWT).

Notice how the /profile route handler can directly access req.user because the attachUserInfo middleware ran first.

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

// Middleware to attach user info (mock data)
const attachUserInfo = (req, res, next) => {
  req.user = { id: '123', name: 'Alice', role: 'admin' };
  console.log('User info attached to request.');
  next();
};

// Apply the middleware globally
app.use(attachUserInfo);

// Route that uses the attached user info
app.get('/profile', (req, res) => {
  res.send(`Welcome, ${req.user.name}! Your role is: ${req.user.role}`);
});

app.get('/', (req, res) => {
  res.send('Home page (no user info explicitly needed here)');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Building Middleware Chains

You can chain multiple middleware functions together. Express executes them in the order they are defined. Each middleware must call next() to pass control to the next one.

  • This allows you to break down complex request processing into smaller, manageable, and reusable functions.
  • For example, you could have a middleware for authentication, then one for logging, then one for parsing, all before your final route handler.

Conditional Middleware Execution

Sometimes you only want middleware to run under certain conditions. You can achieve this by:

  • Route-specific application: As seen, applying middleware directly to app.get(), app.post(), etc.
  • Internal logic: Adding conditional checks (if statements) inside the middleware itself.
  • Custom wrapper functions: Creating a function that returns a middleware based on parameters.

Practical: Request Timer Middleware

Let's build a middleware that measures how long it takes for a request to be processed and a response to be sent. This is very useful for performance monitoring.

This example uses res.on('finish', ...) to execute code AFTER the response has been sent to the client.

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

// Middleware to measure request duration
const requestTimer = (req, res, next) => {
  const start = Date.now(); // Record start time
  res.on('finish', () => { // Listen for the response 'finish' event
    const end = Date.now(); // Record end time
    const duration = end - start;
    console.log(`${req.method} ${req.originalUrl} took ${duration}ms`);
  });
  next(); // Pass control
};

// Apply the timer middleware
app.use(requestTimer);

// Define a route that simulates some work
app.get('/slow', (req, res) => {
  setTimeout(() => {
    res.send('This was a slow response!');
  }, 500); // Simulate 500ms delay
});

app.get('/', (req, res) => {
  res.send('Hello, fast world!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Middleware Function Quiz

Consider a custom middleware function defined as const myMiddleware = (req, res, next) => { /* ... */ };

Which of the following statements about its behavior is TRUE?

Custom Middleware Recap

You've learned how to create and use custom Express middleware!

  • Custom middleware functions have the signature (req, res, next).
  • Calling next() is crucial to pass control to the next middleware or route handler.
  • Middleware can modify the req and res objects, making data available downstream.
  • You can apply middleware globally with app.use() or to specific routes.
  • They are powerful for adding reusable logic like logging, authentication, or request timing.

Mastering custom middleware is key to building modular and efficient Express applications.

자주 묻는 질문

“사용자 정의 Express 미들웨어 개발” 강의는 무료인가요?

네 — “사용자 정의 Express 미들웨어 개발” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 정의 Express 미들웨어 개발”에서 뭘 배우나요?

직접 Express 미들웨어 함수를 작성하여 기능을 확장하고 요청 처리를 간소화합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“사용자 정의 Express 미들웨어 개발” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사용자 정의 Express 미들웨어 개발
  2. 전역 오류 처리 전략
  3. Joi/Express-Validator로 입력값 검증
  4. JWT를 사용한 인증 미들웨어
← Node.js Backend Development Bootcamp(으)로 돌아가기