라우팅 및 미들웨어
라우팅 라이브러리와 미들웨어 패턴을 활용하여 Worker API를 체계적으로 구성하고 개선합니다.
라우팅 및 미들웨어은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Edge Computing with Cloudflare Workers & Deno 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
API Routing Essentials
When building APIs, we need a way to direct incoming requests to the correct functions based on their URL path and HTTP method (GET, POST, etc.). This process is called routing.
Think of it like a receptionist for your API. When a request comes in, the router checks its destination and sends it to the right department (your code handler).
Manual Worker Routing
In a Cloudflare Worker, all incoming requests are handled by the fetch event listener. You can manually inspect the request's URL and method to decide what to do.
While possible for simple cases, this approach quickly becomes complex and hard to manage as your API grows.
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === '/hello' && request.method === 'GET') {
return new Response('Hello from manual route!');
}
return new Response('Not Found', { status: 404 });
}
}Introducing itty-router
To simplify routing, we use lightweight libraries. For Cloudflare Workers, itty-router is a popular choice. It's tiny, fast, and designed for the edge.
It provides a clean, expressive way to define routes and handlers, making your Worker code much more organized.
Basic GET Routes
With itty-router, you can define routes using methods like router.get() for GET requests. Each route takes a path and a handler function.
Let's create a simple Worker that responds to / and /greet.
import { Router } from 'itty-router';
const router = Router();
router.get('/', () => new Response('Welcome to the API!'));
router.get('/greet', () => new Response('Hello there!'));
export default {
fetch: router.handle
};Handling All HTTP Methods
itty-router allows you to define routes for specific HTTP methods like .post(), .put(), .delete(), and more.
You can also use .all() to match any HTTP method for a given path, useful for middleware or generic handlers.
import { Router } from 'itty-router';
const router = Router();
router.get('/data', () => new Response('GET data'));
router.post('/data', () => new Response('POST data', { status: 201 }));
router.all('*', () => new Response('Method Not Allowed', { status: 405 }));
export default {
fetch: router.handle
};Dynamic Route Parameters
Often, you need to extract dynamic values from the URL, like an item ID or a username. These are called route parameters.
itty-router uses a colon (:) to define parameters in a route path. The values are then available in the handler's request.params object.
import { Router } from 'itty-router';
const router = Router();
router.get('/users/:id', ({ params }) => {
return new Response(`Fetching user ${params.id}`);
});
export default {
fetch: router.handle
};What is Middleware?
Middleware functions are code snippets that run before or after your main route handler. They can modify the request, perform logging, check authentication, or add headers to the response.
They act as a pipeline, allowing you to add common functionalities across multiple routes without duplicating code.
Implementing Simple Middleware
With itty-router, middleware can be added to specific routes or globally. A middleware function receives the request and can return a response (ending the chain) or continue to the next handler.
Let's add a simple logging middleware that runs for every request.
import { Router } from 'itty-router';
const router = Router();
const loggerMiddleware = async (request, event) => {
console.log(`Request: ${request.method} ${request.url}`);
// To proceed to the next handler, don't return a Response.
// If you return a Response, the chain stops.
};
router.all('*', loggerMiddleware);
router.get('/hello', () => new Response('Hello from route!'));
export default {
fetch: router.handle
};Chaining Middleware
You can chain multiple middleware functions. Each middleware executes in order. If a middleware doesn't return a response, the next one in the chain (or the final route handler) is called.
This allows for powerful, modular processing of requests, like authentication, data parsing, and logging.
import { Router } from 'itty-router';
const router = Router();
const authMiddleware = async (request) => {
if (request.headers.get('Authorization') !== 'Bearer token123') {
return new Response('Unauthorized', { status: 401 });
}
};
const headerMiddleware = async (request, event) => {
// Add a custom header to the response later
event.response = new Response('', { headers: { 'X-Powered-By': 'CoddyKit' } });
};
router.get('/secure', authMiddleware, (request) => {
return new Response('Access granted!');
});
router.get('/info', headerMiddleware, (request) => {
return new Response('Info page');
});
export default {
fetch: async (request, env, ctx) => {
const response = await router.handle(request, env, ctx);
// Merge headers from middleware if present
if (ctx.response && response) {
for (let [key, value] of ctx.response.headers.entries()) {
response.headers.set(key, value);
}
}
return response;
}
};Routing & Middleware Check
Consider a Cloudflare Worker using itty-router. You want to ensure that all requests to /admin/* paths require an X-Admin-Key header, and if it's missing, return a 403 Forbidden response. Other paths should not be affected.
Recap: Routing & Middleware
You've mastered the fundamentals of organizing your edge API with routing and middleware!
- Routing directs requests to the right handlers.
- Libraries like
itty-routersimplify route definition, including dynamic parameters. - Middleware functions enhance requests/responses, adding common logic like logging or authentication before (or after) the main handler.
These patterns are crucial for building scalable and maintainable serverless APIs at the edge.
자주 묻는 질문
“라우팅 및 미들웨어” 강의는 무료인가요?
네 — “라우팅 및 미들웨어” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 3개의 강의가 포함되어 있습니다.
“라우팅 및 미들웨어”에서 뭘 배우나요?
라우팅 라이브러리와 미들웨어 패턴을 활용하여 Worker API를 체계적으로 구성하고 개선합니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“라우팅 및 미들웨어” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- RESTful API 설계
- 라우팅 및 미들웨어
- 검증 및 오류 처리