Core API Reference
Complete API reference for @curisjs/core package.
Source Code
All source code is available on GitHub
Application
Class: Application
Source View on GitHubThe main application class that handles routing and middleware.
Constructor
new Application(options?: ApplicationOptions)Parameters:
options(optional): Application configuration options
Example:
import { Application } from '@curisjs/core';
const app = new Application();Methods
get(path, ...handlers)
Register a GET route.
Signature:
get(path: string, ...handlers: Handler[]): ApplicationParameters:
path: Route path patternhandlers: One or more handler functions
Returns: Application instance for chaining
Example:
app.get('/users', (ctx) => ctx.json({ users: [] }));
app.get('/users/:id', authMiddleware, (ctx) => {
return ctx.json({ id: ctx.params.id });
});post(path, ...handlers)
Register a POST route.
Signature:
post(path: string, ...handlers: Handler[]): ApplicationParameters:
path: Route path patternhandlers: One or more handler functions
Returns: Application instance for chaining
Example:
app.post('/users', async (ctx) => {
const data = await ctx.request.json();
return ctx.json({ user: data }, { status: 201 });
});put(path, ...handlers)
Register a PUT route.
Signature:
put(path: string, ...handlers: Handler[]): Applicationpatch(path, ...handlers)
Register a PATCH route.
Signature:
patch(path: string, ...handlers: Handler[]): Applicationdelete(path, ...handlers)
Register a DELETE route.
Signature:
delete(path: string, ...handlers: Handler[]): Applicationhead(path, ...handlers)
Register a HEAD route.
Signature:
head(path: string, ...handlers: Handler[]): Applicationoptions(path, ...handlers)
Register an OPTIONS route.
Signature:
options(path: string, ...handlers: Handler[]): Applicationall(path, ...handlers)
Register a route that matches all HTTP methods.
Signature:
all(path: string, ...handlers: Handler[]): Applicationuse(...handlers)
Register global middleware.
Signature:
use(...handlers: Handler[]): ApplicationParameters:
handlers: One or more middleware functions
Returns: Application instance for chaining
Example:
import { logger, cors } from '@curisjs/core/middleware';
app.use(logger());
app.use(cors());
app.use(async (ctx, next) => {
ctx.state.requestTime = Date.now();
await next();
});listen(options)
Start the HTTP server (Node.js only).
Signature:
listen(options: ListenOptions): ServerParameters:
options.port: Port number (default: 3000)options.host: Host address (default: 'localhost')options.callback: Optional callback when server starts
Returns: Node.js HTTP Server instance
Example:
app.listen({
port: 3000,
callback: () => console.log('Server running on port 3000')
});fetch(request, env?)
Handle a Web Standard Request (for edge runtimes).
Signature:
fetch(request: Request, env?: any): Promise<Response>Parameters:
request: Web Standard Request objectenv: Optional environment object (for Cloudflare Workers, etc.)
Returns: Promise resolving to Web Standard Response
Example:
// Bun
Bun.serve({ port: 3000, fetch: app.fetch });
// Deno
Deno.serve({ port: 3000 }, app.fetch);
// Cloudflare Workers
export default { fetch: app.fetch };Context
Interface: Context
Source View on GitHubThe context object passed to all handlers and middleware.
Properties
request
Type: Request
The Web Standard Request object.
Example:
const method = ctx.request.method;
const headers = ctx.request.headers;params
Type: Record<string, string>
Route parameters extracted from the URL path.
Example:
// Route: /users/:id
app.get('/users/:id', (ctx) => {
const userId = ctx.params.id;
});url
Type: URL
Parsed URL object.
Example:
const pathname = ctx.url.pathname;
const search = ctx.url.searchParams.get('q');state
Type: Record<string, any>
State object for sharing data between middleware.
Example:
app.use((ctx, next) => {
ctx.state.user = { id: 1 };
return next();
});Methods
json(data, options?)
Return a JSON response.
Signature:
json(data: any, options?: ResponseOptions): ResponseParameters:
data: Data to serialize as JSONoptions.status: HTTP status code (default: 200)options.headers: Additional headers
Returns: Response object
Example:
return ctx.json({ message: 'Success' });
return ctx.json({ error: 'Not found' }, { status: 404 });text(text, options?)
Return a plain text response.
Signature:
text(text: string, options?: ResponseOptions): ResponseExample:
return ctx.text('Hello World');html(html, options?)
Return an HTML response.
Signature:
html(html: string, options?: ResponseOptions): ResponseExample:
return ctx.html('<h1>Hello World</h1>');redirect(url, status?)
Redirect to another URL.
Signature:
redirect(url: string, status?: number): ResponseParameters:
url: Target URLstatus: HTTP status code (default: 302)
Example:
return ctx.redirect('/login');
return ctx.redirect('/home', 301); // Permanent redirectstream(stream, options?)
Return a streaming response.
Signature:
stream(stream: ReadableStream, options?: ResponseOptions): Responsesse()
Create a Server-Sent Events stream.
Signature:
sse(): { stream: ReadableStream; send: (data: any) => void; close: () => void }Example:
app.get('/events', (ctx) => {
const { stream, send, close } = ctx.sse();
const interval = setInterval(() => {
send({ time: Date.now() });
}, 1000);
setTimeout(() => {
close();
clearInterval(interval);
}, 10000);
return ctx.stream(stream);
});setHeader(name, value)
Set a response header.
Signature:
setHeader(name: string, value: string): voidgetHeader(name)
Get a request header.
Signature:
getHeader(name: string): string | nullcookie(name, value, options?)
Set a cookie.
Signature:
cookie(name: string, value: string, options?: CookieOptions): voidOptions:
maxAge: Cookie lifetime in secondsexpires: Expiration datepath: Cookie pathdomain: Cookie domainsecure: HTTPS onlyhttpOnly: Not accessible via JavaScriptsameSite: 'Strict' | 'Lax' | 'None'
Example:
ctx.cookie('session', 'abc123', {
httpOnly: true,
secure: true,
maxAge: 86400, // 1 day
sameSite: 'Strict'
});getCookie(name)
Get a cookie value.
Signature:
getCookie(name: string): string | undefinedTypes
Source View on GitHubHandler
Request handler or middleware function.
type Handler = (ctx: Context, next: Next) => Response | Promise<Response> | void | Promise<void>Next
Function to call the next middleware in the chain.
type Next = () => Promise<void>Middleware
Alias for Handler type.
type Middleware = HandlerRouteHandler
Route-specific handler (no next function).
type RouteHandler = (ctx: Context) => Response | Promise<Response>ApplicationOptions
Configuration options for Application.
interface ApplicationOptions {
// Future options
}ListenOptions
Options for starting the server.
interface ListenOptions {
port?: number;
host?: string;
callback?: () => void;
}ResponseOptions
Options for response helpers.
interface ResponseOptions {
status?: number;
headers?: Record<string, string>;
}CookieOptions
Options for setting cookies.
interface CookieOptions {
maxAge?: number;
expires?: Date;
path?: string;
domain?: string;
secure?: boolean;
httpOnly?: boolean;
sameSite?: 'Strict' | 'Lax' | 'None';
}Middleware
Source View on GitHubBuilt-in Middleware
logger(options?)
Request logging middleware.
Signature:
logger(options?: LoggerOptions): MiddlewareOptions:
format: Log format ('combined' | 'common' | 'short' | 'tiny')
Example:
import { logger } from '@curisjs/core/middleware';
app.use(logger({ format: 'combined' }));cors(options?)
CORS middleware.
Signature:
cors(options?: CorsOptions): MiddlewareOptions:
origin: Allowed originsmethods: Allowed methodsallowedHeaders: Allowed headersexposedHeaders: Exposed headerscredentials: Allow credentialsmaxAge: Preflight cache duration
Example:
import { cors } from '@curisjs/core/middleware';
app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
credentials: true
}));Validation
Source View on GitHubz Object
Zod-like schema validation.
String Schema
z.string(): StringSchemaMethods:
.min(n): Minimum length.max(n): Maximum length.email(): Email validation.url(): URL validation.uuid(): UUID validation.regex(pattern): Regex validation.optional(): Make optional.nullable(): Allow null
Example:
import { z } from '@curisjs/core';
const schema = z.string().min(3).max(50).email();Number Schema
z.number(): NumberSchemaMethods:
.min(n): Minimum value.max(n): Maximum value.positive(): Positive numbers only.negative(): Negative numbers only.int(): Integers only
Boolean Schema
z.boolean(): BooleanSchemaObject Schema
z.object(shape): ObjectSchemaExample:
const userSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().min(18)
});Array Schema
z.array(elementSchema): ArraySchemaExample:
const tagsSchema = z.array(z.string());Validation Methods
parse(data)
Parse and validate data, throw on error.
const result = schema.parse(data);safeParse(data)
Parse and validate data, return result object.
const result = schema.safeParse(data);
if (result.success) {
console.log(result.data);
} else {
console.log(result.error);
}Utilities
Source View on GitHubjson(data, options?)
Create a JSON response.
import { json } from '@curisjs/core';
return json({ message: 'Success' });text(text, options?)
Create a text response.
import { text } from '@curisjs/core';
return text('Hello World');html(html, options?)
Create an HTML response.
import { html } from '@curisjs/core';
return html('<h1>Hello</h1>');redirect(url, status?)
Create a redirect response.
import { redirect } from '@curisjs/core';
return redirect('/login');Adapters
Source View on GitHubNode.js Adapter
import { nodeAdapter } from '@curisjs/core/adapters';
import { createServer } from 'node:http';
const server = createServer(nodeAdapter(app));
server.listen(3000);Error Handling
Custom Error Classes
class HttpError extends Error {
constructor(
public status: number,
message: string
) {
super(message);
}
}Usage:
app.get('/users/:id', (ctx) => {
const user = findUser(ctx.params.id);
if (!user) {
throw new HttpError(404, 'User not found');
}
return ctx.json({ user });
});Type Inference
Infer Types from Schemas
const userSchema = z.object({
name: z.string(),
email: z.string().email()
});
type User = z.infer<typeof userSchema>;
// { name: string; email: string }Constants
HTTP Status Codes
export const HTTP_STATUS = {
OK: 200,
CREATED: 201,
NO_CONTENT: 204,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500,
} as const;HTTP Methods
export const HTTP_METHODS = [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'HEAD',
'OPTIONS'
] as const;