Set up your router
First, create a router with middleware. The router handles all HTTP requests and applies middleware in order.The
app/router.ts
createRouter function creates a router instance that you can map routes to. Middleware runs for every request before your route handlers.Define your routes
Create a type-safe routes definition using the Each route maps to an HTTP method and path pattern. Path parameters like
routes helper. This provides autocomplete and type checking.app/routes.ts
:id are automatically extracted and typed.Create a controller
Controllers group related route handlers together. Each action receives a request context with typed params.The
app/users.ts
satisfies operator ensures your controller matches the routes structure, providing full type safety.Map controllers to routes
Connect your controller to the router using the You can also map individual routes:
map method:app/router.ts
Add request validation
Use middleware to validate requests before they reach your handlers:Apply it to specific controllers:
app/middleware/validate.ts
app/users.ts
Handle errors
Add error handling middleware to catch and format errors:Add it as the first middleware:
app/middleware/errors.ts
app/router.ts
API Best Practices
Use proper HTTP status codes
200 OK- Successful GET, PATCH, PUT201 Created- Successful POST that creates a resource204 No Content- Successful DELETE400 Bad Request- Invalid request data404 Not Found- Resource doesn’t exist500 Internal Server Error- Server error