HTTP Helpers
The request and response objects are globally accessible anywhere from request contexts. This guide covers helper functions for interacting with HTTP requests and responses.
Quick Reference
Request Helpers
request()- Get native Request objectrequest.url()- Get URL objectrequest.ip()- Get client IP addressheaders()- Get request headerssearchParams()- Get query string parametersparams()- Get route parametersbody()- Get request body
Response Helpers
response()- Get native Response objectresponse.status()- Set status codeheaders.set()- Set response headers
Customization
app.serialize- Global serializationtransformhook - Modify data before serializationsendhook - Modify response before sending
Request
request()
Retrieves the native Web API Request object.
import { request } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getURL() {
const req = request();
return req.url;
}
export const routes: Routes = {
"GET /": getURL,
};You can use request() in nested function calls:
import { request } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function fetchURL() {
return request().url;
}
function getURL() {
return fetchURL();
}
export const routes: Routes = {
"GET /": getURL,
};request.url()
Returns the parsed URL object from the request.
import { request } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getUsers() {
const url = request.url();
console.log(url.pathname); // "/users"
console.log(url.searchParams.get("page")); // query param
return { path: url.pathname };
}
export const routes: Routes = {
"GET /users": getUsers,
};request.ip()
Returns the client's IP address. Requires the Proxy plugin to be registered and configured.
Configuration:
Before using request.ip(), register the IP plugin (often via proxy):
import { request } from "@minimajs/server";
import { proxy } from "@minimajs/server/plugins";
// Use custom header (e.g., Cloudflare)
app.register(proxy({ trustProxies: true, ip: { header: "CF-Connecting-IP" } }));Example:
import type { Routes } from "@minimajs/server";
function getIP() {
const ip = request.ip();
return { clientIp: ip };
}
export const routes: Routes = {
"GET /": getIP,
};Headers
headers()
Returns the request headers. Supports direct access and transformation utilities.
import { headers } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getHeaders() {
const reqHeaders = headers();
const auth = reqHeaders.get("authorization");
return { auth };
}
export const routes: Routes = {
"GET /": getHeaders,
};headers.get()
Gets a single header value with optional transformation.
import { headers } from "@minimajs/server";
// Get as string
const contentType = headers.get("content-type");
// Transform to number
const contentLength = headers.get("content-length", Number);headers.getAll()
Gets all values for a header with optional transformation.
import { headers } from "@minimajs/server";
// Get all values
const cookies = headers.getAll("cookie");
// Transform each value
const lengths = headers.getAll("x-custom", Number);Search Params
searchParams()
Returns the URL search parameters (query string).
import { searchParams } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function search() {
const params = searchParams();
const query = params.get("q");
return { query };
}
export const routes: Routes = {
"GET /search": search,
};searchParams.get()
Gets a single query parameter with optional transformation.
import { searchParams } from "@minimajs/server";
// Get as string
const query = searchParams.get("q");
// Transform to number
const page = searchParams.get("page", Number);searchParams.getAll()
Gets all values for a query parameter with optional transformation.
import { searchParams } from "@minimajs/server";
// Get all values
const tags = searchParams.getAll("tag");
// Transform each value
const ids = searchParams.getAll("id", Number);Route Params
params()
Returns the route parameters.
import { params } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getUser() {
const routeParams = params();
const userId = routeParams.get("id");
return { userId };
}
export const routes: Routes = {
"GET /users/:id": getUser,
};params.get()
Gets a route parameter with optional transformation.
import { params } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getUser() {
// Get as string
const userId = params.get("id");
// Transform to number
const numericId = params.get("id", Number);
return { userId, numericId };
}
export const routes: Routes = {
"GET /users/:id": getUser,
};Request Body
body()
Returns the parsed request body. The body parser is enabled by default and configured to parse JSON, so you can use body() immediately without any setup.
import { body } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function createUser() {
const data = body();
return { created: data };
}
// Body parser is already enabled - no registration needed!
export const routes: Routes = {
"POST /users": createUser,
};To change the configuration or disable the body parser, see the Body Parser plugin documentation.
Response
response()
Returns the native Response object for the current request context.
import { response } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getResponse() {
const res = response();
console.log(res.status); // 200
return "Hello";
}
export const routes: Routes = {
"GET /": getResponse,
};response.status()
Sets the HTTP status code for the response.
import { response } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function throwError() {
response.status(500);
return { error: "Internal Server Error" };
}
function createItem() {
response.status(201);
return { id: 123 };
}
export const routes: Routes = {
"GET /error": throwError,
"POST /created": createItem,
};headers.set()
Sets response headers.
import { headers } from "@minimajs/server";
import type { Routes } from "@minimajs/server";
function getHome() {
headers.set("X-Custom-Header", "value");
headers.set("Content-Type", "application/json");
return { message: "Hello" };
}
export const routes: Routes = {
"GET /": getHome,
};Modifying Response
Custom Serializer: app.serialize
Define global serialization logic for all responses.
import { createApp } from "@minimajs/server";
const app = createApp();
app.serialize = function serialize(data) {
return JSON.stringify({ success: true, data });
};
app.get("/users", () => {
return [{ id: 1, name: "Alice" }];
// Response: {"success":true,"data":[{"id":1,"name":"Alice"}]}
});Use cases:
- Add global response wrappers
- Custom encoding formats
- Consistent API response structure
Modifying Response Data: transform Hook
Use the transform hook to modify response data before serialization.
import { hook } from "@minimajs/server";
// Add timestamp to all responses
hook("transform", (data) => {
return { ...data, timestamp: Date.now() };
});
app.get("/users", () => {
return { users: [] };
// Response: {"users":[],"timestamp":1234567890}
});See Transform Hook for more details.
Post-Response Tasks: send Hook
Use the send hook to execute tasks after the response is sent, such as logging or cleanup.
import { hook } from "@minimajs/server";
// Log all responses after they're sent
hook("send", (response, ctx) => {
console.log(`Response sent: ${response.status} for ${ctx.pathname}`);
});
app.get("/", () => "Hello");
// Logs: Response sent: 200 for /See Send Hook for more details.
Related Guides
- Hooks - Request lifecycle and hook system
- Error Handling - Error handling patterns
- Context - Request context management