API Reference
Complete reference for all EdgeMaster classes, methods, and utilities.
Quick Navigation
Core Classes
- EdgeController - Main application orchestrator
- RouteHandler - Route handler with task execution
- Task - Individual units of work
Helper Functions
Response Helpers:
- json() - JSON response
- text() - Text response
- html() - HTML response
- redirect() - Redirect response
- notFound() - 404 response
- badRequest() - 400 response
- unauthorized() - 401 response
- forbidden() - 403 response
- serverError() - 500 response
Request Helpers:
- parseJSON() - Parse JSON body
- parseFormData() - Parse form data
- parseText() - Parse text body
- parseQuery() - Parse query parameters
- getQuery() - Get single query parameter
Context Helpers:
- setState() - Set context state
- getState() - Get context state
- hasState() - Check if state exists
- deleteState() - Delete state value
Interceptors
- corsInterceptor() - CORS support
- loggingInterceptor() - Request/response logging
- cacheInterceptor() - Cloudflare Cache API
- rateLimitInterceptor() - Rate limiting
- jwtInterceptor() - JWT authentication
- apiKeyInterceptor() - API key authentication
EdgeController
The main orchestrator for your edge application.
Constructor
const app = new EdgeController();
HTTP Method Helpers
GET()
Register a GET route.
GET(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
Parameters:
pattern- URL pattern (e.g.,/users,/users/:id)handler- RouteHandler instancepriority- Optional priority (higher = matched first)
Example:
app.GET('/users', new RouteHandler(new Task({
do: async () => json({ users: [] })
})));
POST()
Register a POST route.
POST(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
Example:
app.POST('/users', new RouteHandler(new Task({
do: async ({ req }) => {
const body = await parseJSON(req);
return json({ user: body }, { status: 201 });
}
})));
PUT()
Register a PUT route.
PUT(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
DELETE()
Register a DELETE route.
DELETE(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
PATCH()
Register a PATCH route.
PATCH(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
HEAD()
Register a HEAD route.
HEAD(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
OPTIONS()
Register an OPTIONS route.
OPTIONS(pattern: string, handler: IRouteHandler, priority?: number): EdgeController
Route Management
addRoute()
Add a custom route with matcher.
addRoute(matcher: IMatcher, handler: IRouteHandler, priority?: number): EdgeController
Parameters:
matcher- Function that returns true if route matcheshandler- RouteHandler instancepriority- Optional priority (higher = matched first)
Example:
app.addRoute(
(req) => new URL(req.url).pathname.startsWith('/admin'),
adminHandler,
100
);
group()
Group routes under a common prefix.
group(prefix: string, configure: (group: EdgeController) => void): EdgeController
Example:
app.group('/api/v1', (api) => {
api.GET('/users', listUsersHandler);
api.POST('/users', createUserHandler);
api.GET('/posts', listPostsHandler);
});
// Creates routes:
// GET /api/v1/users
// POST /api/v1/users
// GET /api/v1/posts
Nested Groups:
app.group('/api', (api) => {
api.group('/v1', (v1) => {
v1.GET('/users', usersV1Handler);
});
api.group('/v2', (v2) => {
v2.GET('/users', usersV2Handler);
});
});
Interceptor Management
addInterceptor()
Add request or response interceptor.
addInterceptor(interceptor: IInterceptor): EdgeController
Example:
import { corsInterceptor, loggingInterceptor } from 'edge-master';
app.addInterceptor(corsInterceptor({ origin: '*' }));
const { request, response } = loggingInterceptor();
app.addInterceptor(request);
app.addInterceptor(response);
Error Handling
onNotFound()
Set custom 404 handler.
onNotFound(handler: (ctx: Context) => Response | Promise<Response>): EdgeController
Example:
app.onNotFound(async ({ req }) => {
const url = new URL(req.url);
return json({
error: 'Not Found',
path: url.pathname
}, { status: 404 });
});
onError()
Set custom error handler.
onError(handler: (error: Error, ctx: Context) => Response | Promise<Response>): EdgeController
Example:
app.onError(async (error, ctx) => {
console.error('Error:', error);
return json({
error: 'Internal Server Error',
message: error.message
}, { status: 500 });
});
Request Handling
handleRequest()
Process incoming request.
handleRequest(args: RequestHandlerArgs): Promise<Response>
Parameters:
type RequestHandlerArgs = {
req: Request;
env?: any;
ctx?: ExecutionContext;
}
Example:
export default {
fetch: (request: Request, env: any, ctx: ExecutionContext) => {
return app.handleRequest({ req: request, env, ctx });
}
};
RouteHandler
Manages sequential task execution for routes.
Constructor
new RouteHandler(...tasks: Task[])
Example:
const handler = new RouteHandler(
new Task({
do: async ({ req }) => {
// Task 1
console.log('Validating request...');
return req;
}
}),
new Task({
do: async () => {
// Task 2
return json({ message: 'Success' });
}
})
);
Methods
handle()
Execute all tasks sequentially.
handle(ctx: Context): Promise<Response>
Task
Individual units of work with optional conditions.
Constructor
new Task(config: {
do: (ctx: Context) => any | Promise<any>;
if?: (ctx: Context) => boolean | Promise<boolean>;
else?: (ctx: Context) => any | Promise<any>;
})
Parameters:
do- Main task functionif- Optional condition (task runs if true)else- Optional else branch (runs if condition is false)
Basic Task
new Task({
do: async () => json({ message: 'Hello' })
})
Conditional Task
new Task({
if: async ({ req }) => {
const user = getState(ctx, 'user');
return user?.role === 'admin';
},
do: async () => json({ data: 'admin data' }),
else: async () => unauthorized('Admin only')
})
Response Helpers
json()
Create JSON response.
json(data: any, init?: ResponseInit): Response
Example:
return json({ users: [] });
return json({ error: 'Invalid' }, { status: 400 });
text()
Create text response.
text(data: string, init?: ResponseInit): Response
html()
Create HTML response.
html(data: string, init?: ResponseInit): Response
redirect()
Create redirect response.
redirect(location: string, status: number = 302): Response
Example:
return redirect('/new-path');
return redirect('/login', 301);
notFound()
Create 404 response.
notFound(message: string = 'Not Found'): Response
badRequest()
Create 400 response.
badRequest(message: string = 'Bad Request'): Response
unauthorized()
Create 401 response.
unauthorized(message: string = 'Unauthorized'): Response
forbidden()
Create 403 response.
forbidden(message: string = 'Forbidden'): Response
serverError()
Create 500 response.
serverError(message: string = 'Internal Server Error'): Response
Request Helpers
parseJSON()
Parse JSON request body.
parseJSON<T = any>(req: Request): Promise<T>
Example:
const body = await parseJSON(req);
console.log(body.name, body.email);
Throws: RequestParseError if parsing fails.
parseFormData()
Parse form data.
parseFormData(req: Request): Promise<FormData>
parseText()
Parse text body.
parseText(req: Request): Promise<string>
parseQuery()
Get all query parameters.
parseQuery(req: Request): URLSearchParams
Example:
const params = parseQuery(req);
const page = params.get('page') || '1';
const limit = params.get('limit') || '10';
getQuery()
Get single query parameter.
getQuery(req: Request, key: string): string | null
Example:
const search = getQuery(req, 'q');
const page = getQuery(req, 'page') || '1';
Context Helpers
setState()
Set value in context state.
setState<T = any>(ctx: Context, key: string, value: T): void
Example:
setState(ctx, 'user', { id: '123', name: 'Alice' });
setState(ctx, 'requestId', crypto.randomUUID());
getState()
Get value from context state.
getState<T = any>(ctx: Context, key: string): T | undefined
Example:
const user = getState<User>(ctx, 'user');
if (user) {
console.log(user.name);
}
hasState()
Check if state key exists.
hasState(ctx: Context, key: string): boolean
deleteState()
Delete state value.
deleteState(ctx: Context, key: string): boolean
Interceptors
corsInterceptor()
Add CORS support.
corsInterceptor(options?: {
origin?: string | string[];
methods?: string[];
allowedHeaders?: string[];
exposedHeaders?: string[];
credentials?: boolean;
maxAge?: number;
}): IRequestInterceptor
Example:
app.addInterceptor(corsInterceptor({
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true
}));
loggingInterceptor()
Add request/response logging.
loggingInterceptor(options?: {
level?: 'debug' | 'info' | 'warn' | 'error';
logTiming?: boolean;
logHeaders?: boolean;
logBody?: boolean;
}): {
request: IRequestInterceptor;
response: IResponseInterceptor;
}
Example:
const { request, response } = loggingInterceptor({
level: 'info',
logTiming: true
});
app.addInterceptor(request);
app.addInterceptor(response);
cacheInterceptor()
Add Cloudflare Cache API support.
cacheInterceptor(options: {
ttl: number;
methods?: string[];
varyHeaders?: string[];
cacheKey?: (req: Request) => string;
}): {
check: IRequestInterceptor;
store: IResponseInterceptor;
}
Example:
const { check, store } = cacheInterceptor({
ttl: 3600,
methods: ['GET', 'HEAD']
});
app.addInterceptor(check);
app.addInterceptor(store);
rateLimitInterceptor()
Add rate limiting.
rateLimitInterceptor(options: {
limit: number;
window: number;
storage: IRateLimitStorage;
keyGenerator?: (req: Request) => string;
onLimit?: (req: Request) => Response;
}): IRequestInterceptor
Example:
import { MemoryRateLimitStorage } from 'edge-master';
app.addInterceptor(rateLimitInterceptor({
limit: 100,
window: 60000,
storage: new MemoryRateLimitStorage()
}));
jwtInterceptor()
Add JWT authentication.
jwtInterceptor(options: {
verify: (token: string, req: Request) => Promise<any> | any;
exclude?: string[];
extractToken?: (req: Request) => string | null;
onError?: (error: Error) => Response;
}): IRequestInterceptor
Example:
app.addInterceptor(jwtInterceptor({
verify: async (token) => verifyJWT(token, env.JWT_SECRET),
exclude: ['/auth/login', '/auth/register']
}));
apiKeyInterceptor()
Add API key authentication.
apiKeyInterceptor(options: {
validate: (key: string, req: Request) => Promise<boolean> | boolean;
exclude?: string[];
headerName?: string;
onError?: (error: Error) => Response;
}): IRequestInterceptor
Utility Functions
pathMatcher()
Create path pattern matcher.
pathMatcher(pattern: string): IMatcher
Supports:
- Exact paths:
/users - Parameters:
/users/:id - Wildcards:
/assets/*
httpMethod()
Create HTTP method matcher.
httpMethod(method: string): IMatcher
and()
Combine matchers with AND logic.
and(...matchers: IMatcher[]): IMatcher
Example:
app.addRoute(
and(httpMethod('GET'), pathMatcher('/admin/*')),
adminHandler
);
or()
Combine matchers with OR logic.
or(...matchers: IMatcher[]): IMatcher
Types & Interfaces
For complete type definitions, see the Data Models section.
Error Classes
RequestParseError
Thrown when request parsing fails.
class RequestParseError extends Error {
constructor(message: string, public cause?: Error);
}
Example:
try {
const body = await parseJSON(req);
} catch (error) {
if (error instanceof RequestParseError) {
return badRequest('Invalid JSON');
}
}
Next Steps
- View Examples - See real-world usage
- Best Practices - Learn recommended patterns
- Core Concepts - Understand the architecture
Questions? Open an issue or email us