Powerful routing system with pattern matching, parameter extraction, and route-specific configuration options for handling HTTP requests in @hapi/hapi.
Add routes to the server with flexible configuration options.
/**
* Register one or more routes with the server
* @param route - Single route configuration or array of route configurations
*/
route(route: RouteConfiguration | RouteConfiguration[]): void;
interface RouteConfiguration {
/** HTTP method(s) - string or array of strings */
method: string | string[];
/** Route path pattern with optional parameters */
path: string;
/** Route handler function or handler configuration object */
handler: RouteHandler | HandlerObject;
/** Optional route-specific configuration */
options?: RouteOptions;
}
type RouteHandler = (request: Request, h: ResponseToolkit) => any;
interface HandlerObject {
[key: string]: any;
}Usage Examples:
const server = Hapi.server({ port: 3000 });
// Simple route
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
// Multiple methods
server.route({
method: ['GET', 'POST'],
path: '/api/data',
handler: (request, h) => {
return { method: request.method, data: request.payload };
}
});
// Route with parameters
server.route({
method: 'GET',
path: '/users/{id}',
handler: (request, h) => {
return { userId: request.params.id };
}
});
// Multiple routes at once
server.route([
{
method: 'GET',
path: '/health',
handler: () => ({ status: 'ok' })
},
{
method: 'GET',
path: '/version',
handler: () => ({ version: '1.0.0' })
}
]);Flexible path patterns with parameter extraction and wildcards.
// Path parameter patterns:
// '/users/{id}' - Required parameter
// '/users/{id?}' - Optional parameter
// '/users/{id*}' - Multi-segment parameter
// '/files/{path*}' - Catch-all parameter
// '/users/{id}/posts/{postId}' - Multiple parametersUsage Examples:
// Required parameter
server.route({
method: 'GET',
path: '/users/{id}',
handler: (request, h) => {
return { userId: request.params.id };
}
});
// Optional parameter
server.route({
method: 'GET',
path: '/search/{query?}',
handler: (request, h) => {
const query = request.params.query || 'default';
return { query: query };
}
});
// Multi-segment parameter
server.route({
method: 'GET',
path: '/files/{path*}',
handler: (request, h) => {
return { filePath: request.params.path };
}
});
// Multiple parameters
server.route({
method: 'GET',
path: '/users/{userId}/posts/{postId}',
handler: (request, h) => {
return {
userId: request.params.userId,
postId: request.params.postId
};
}
});Comprehensive route-specific configuration options.
interface RouteOptions {
/** Authentication requirements */
auth?: string | boolean | AuthRouteOptions;
/** Context binding override */
bind?: object;
/** Caching configuration */
cache?: CacheRouteOptions;
/** CORS configuration */
cors?: boolean | CorsRouteOptions;
/** Route-level extensions */
ext?: ExtensionRouteOptions;
/** File serving options */
files?: FilesRouteOptions;
/** Handler configuration when using handler objects */
handler?: object;
/** Route identifier */
id?: string;
/** Whether route is internal only */
isInternal?: boolean;
/** JSON parsing options */
json?: JsonRouteOptions;
/** JSONP callback parameter name */
jsonp?: string;
/** Route logging configuration */
log?: LogRouteOptions;
/** Documentation notes */
notes?: string | string[];
/** Request payload options */
payload?: PayloadRouteOptions;
/** Plugin-specific options */
plugins?: object;
/** Pre-handler processing */
pre?: PreRouteOptions[];
/** Response options */
response?: ResponseRouteOptions;
/** Security headers */
security?: SecurityRouteOptions;
/** Cookie state options */
state?: StateRouteOptions;
/** Route tags for organization */
tags?: string[];
/** Request timeout */
timeout?: TimeoutRouteOptions;
/** Input validation */
validate?: ValidateRouteOptions;
/** Virtual host */
vhost?: string | string[];
}Usage Examples:
// Route with options
server.route({
method: 'POST',
path: '/api/users',
options: {
auth: 'jwt',
validate: {
payload: Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required()
})
},
tags: ['api', 'users'],
notes: 'Create a new user account'
},
handler: async (request, h) => {
const user = await createUser(request.payload);
return h.response(user).code(201);
}
});Find registered routes by ID or match routes against method and path.
/**
* Find a route by its ID
* @param id - Route identifier
* @returns Route information or null if not found
*/
lookup(id: string): RoutePublic | null;
/**
* Match a route against method and path
* @param method - HTTP method
* @param path - Request path
* @param host - Optional host header
* @returns Matched route information or null
*/
match(method: string, path: string, host?: string): RoutePublic | null;
interface RoutePublic {
method: string;
path: string;
vhost?: string;
realm: Realm;
settings: RouteOptions;
fingerprint: string;
}Usage Examples:
// Register route with ID
server.route({
method: 'GET',
path: '/api/status',
options: { id: 'api-status' },
handler: () => ({ status: 'ok' })
});
// Lookup route by ID
const route = server.lookup('api-status');
console.log(route.path); // '/api/status'
// Match route by method and path
const matchedRoute = server.match('GET', '/api/status');
console.log(matchedRoute.method); // 'GET'Get a table of all registered routes.
/**
* Get routing table for all registered routes
* @param host - Optional filter by host
* @returns Array of route information
*/
table(host?: string): RoutePublic[];Usage Examples:
// Get all routes
const allRoutes = server.table();
console.log(allRoutes.length);
// Get routes for specific host
const hostRoutes = server.table('api.example.com');
// Display route information
allRoutes.forEach(route => {
console.log(`${route.method} ${route.path}`);
});Built-in handler types for common use cases.
// Built-in handler types (require additional plugins):
// 'directory' - Serve static files from directory (requires @hapi/inert)
// 'file' - Serve single static file (requires @hapi/inert)
// 'view' - Render templates (requires @hapi/vision)
// 'proxy' - Proxy requests (requires @hapi/h2o2)Usage Examples:
// File handler (requires @hapi/inert plugin)
server.route({
method: 'GET',
path: '/favicon.ico',
handler: {
file: './public/favicon.ico'
}
});
// Directory handler (requires @hapi/inert plugin)
server.route({
method: 'GET',
path: '/static/{param*}',
handler: {
directory: {
path: './public',
redirectToSlash: true,
index: true
}
}
});
// View handler (requires @hapi/vision plugin)
server.route({
method: 'GET',
path: '/profile',
handler: {
view: {
template: 'profile',
context: { user: 'John Doe' }
}
}
});interface AuthRouteOptions {
/** Authentication strategy name */
strategy?: string;
/** Authentication mode */
mode?: 'required' | 'optional' | 'try';
/** Payload authentication */
payload?: boolean | string;
/** Authentication scope */
scope?: string | string[];
/** Authentication entity */
entity?: 'user' | 'app' | 'any';
/** Access requirements */
access?: object[];
}
interface CacheRouteOptions {
/** Cache policy configuration */
policy?: string;
/** Cache expiration in milliseconds */
expiresIn?: number;
/** Cache privacy settings */
privacy?: 'default' | 'public' | 'private';
}
interface PayloadRouteOptions {
/** Allow empty payload */
allow?: string | string[];
/** Default content type */
defaultContentType?: string;
/** Fail action for invalid payload */
failAction?: 'error' | 'log' | 'ignore' | Function;
/** Maximum payload size in bytes */
maxBytes?: number;
/** Multipart options */
multipart?: boolean | object;
/** Parse payload */
parse?: boolean;
/** Payload timeout */
timeout?: number;
/** File uploads */
uploads?: string;
}
interface ValidateRouteOptions {
/** Validate headers */
headers?: object;
/** Validate path parameters */
params?: object;
/** Validate query parameters */
query?: object;
/** Validate payload */
payload?: object;
/** Validate cookie state */
state?: object;
/** Validation failure action */
failAction?: 'error' | 'log' | 'ignore' | Function;
/** Validation options */
options?: object;
}