A simple Express-style router using URLPattern API introduced in NodeJS 24.
The example below will work in a AWS Lambda environment.
First, register the routes:
const router = new URLPatternRouter()
router.get('/api/hello', async (event: APIGatewayProxyEventV2) => {
return import('./hello/GET.js').then(({ handler }) => handler(event))
})Then, in your handler function:
const route = router.match(event.requestContext.http.method, event.rawPath)
if (!route) {
const response = {
statusCode: 404,
body: JSON.stringify({ message: 'Not Found' }),
}
Logger.debug('Response', response)
return response
}
// Reassign the path parameters in the format expected by the route rather than API Gateway
event.pathParameters = route.pathParameters
// Run the handler.
const response = await route.handler(event)
// If the response body isnt JSON parseable, make it so
const contentTypeShouldBeJson = typeof response === 'string' ||
!response.headers?.['Content-Type'] ||
response.headers?.['Content-Type'] === 'application/json';
if (typeof response !== 'string' && response.body && contentTypeShouldBeJson) {
try {
JSON.parse(response.body);
} catch {
response.body = JSON.stringify(response.body);
}
}
return response;