Recipes
Migrating from Express
Express habits and their Kest equivalents: routes, middleware, error handling, sessions, uploads and static files.
Express gives you a router and a chain of functions. Kest gives you the same HTTP model with structure on top: controllers instead of app.get(...) calls, and a pipeline of guards, pipes, interceptors and filters instead of an ordered list of middleware.
Routes
// Express
app.get('/users/:id', async (req, res) => {
const user = await users.find(req.params.id);
if (!user) return res.status(404).json({ error: 'not found' });
res.json(user);
});// Kest
@Controller("/users")
class UsersController(private val users: UserService) {
@Get("/{id}") fun find(@Param id: String): User = users.find(id) ?: throw NotFoundException("not found")
}You return the value (it becomes JSON); you throw an HttpException for an error status. There is no res.json unless you ask for the raw response with @Response.
Middleware and the usual packages
| Express | Kest |
|---|---|
app.use(fn) | useMiddleware(Middleware { request, next -> ... }), optionally for some paths |
express.json(), body-parser | built in; bodies are bound with @Body |
cors | enableCors(...) |
helmet | useSecurityHeaders { ... } |
compression | useCompression() |
cookie-parser | @Cookie and ResponseCookie |
express-session | useSession { ... } (memory or Redis) |
csurf | useCsrf() |
express.static | serveStatic("/assets", "public") |
multer | @FormFile |
morgan | LoggingInterceptor and the structured Logger |
express-rate-limit | throttler (@Throttle, @SkipThrottle), throttler-redis |
jsonwebtoken, OAuth login libraries | JwtModule, Authenticators, @Authenticated |
dotenv | ConfigModule |
express-validator, joi | constraint annotations (@NotBlank, @Email, @Pattern...) |
Errors
Express error middleware (err, req, res, next) becomes a @ControllerAdvice:
@ControllerAdvice
class Errors {
@ExceptionHandler(OrderNotFound::class) @ResponseStatus(404) fun notFound(e: OrderNotFound) = mapOf("error" to e.message)
@ExceptionHandler fun fallback(e: Exception) = mapOf("error" to "internal")
}What you stop doing
- Callbacks, promises and
async: handlers run on virtual threads, so blocking calls (JDBC, HTTP client) are fine and read as straight-line code. - Process managers for CPU use: one process uses every core. Run more processes for isolation or scale, see Running several instances.
- Wiring by import order: providers are declared in modules and injected through constructors.
Steps
- Group routes by resource into controllers; keep paths the same so clients do not notice.
- Turn each
app.useintouseMiddleware, a guard or an interceptor (authentication is a guard). - Replace validation libraries with annotations on request classes.
- Move error middleware to a
@ControllerAdvice. - Start the server:
Kest.run<AppModule>().http(NettyHttpAdapter(8080)) { enableCors(); useCompression() }.