Middlewares
Simple example
To create a middleware that will be ran on every route, simply use '*'
as a path
Sequoia supports using app.use()
as some other frameworks, but provides a better way of declaring everything with routes:
// middlewares-simple.ts
import { Application, HTTPResponse, HTTPStatus, Router } from 'jsr:@sequoia/sequoia'
const app = new Application()
const router = new Router()
// Is going to be ran on every route
router.GET('*', async (context, next) => {
context.response.headers.set('X-Powered-By', 'Sequoia')
console.log('Header middleware')
await next()
})
// Only runs on /user route
router.GET('/user', () => {
console.log('User middleware')
const body = { ok: true, user: { id: 1, name: 'John Doe' } }
return new HTTPResponse({
status: HTTPStatus.SUCCESS,
type: 'application/json',
body
})
})
// Only runs on /post route
router.GET('/post', () => {
console.log('Post middleware')
const body = {
ok: true,
post: {
id: 100,
title: 'Hello World',
content: 'Use Sequoia with Deno'
}
}
return new HTTPResponse({
status: HTTPStatus.SUCCESS,
type: 'application/json',
body
})
})
app.useRouter(router)
await app.listen({ port: 8000 })
Run it with deno run --allow-net middlewares-simple.ts
More complex example
Let's take an Oak example of how to count the time it takes to render a simple Hello world
text by using middlewares
// middlewares-timer.ts
import { Application } from 'jsr:@sequoia/sequoia'
const app = new Application()
const router = new Router()
// Logger
router.GET('*', async (ctx, next) => {
await next()
const rt = ctx.response.headers.get('X-Response-Time')
console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`)
})
// Timing
router.GET('*', async (ctx, next) => {
const start = Date.now()
await next()
const ms = Date.now() - start
ctx.response.headers.set('X-Response-Time', `${ms}ms`)
})
// Hello World!
router.GET('/', () => new HTTPResponse('Hello World!'))
app.useRouter(router)
await app.listen({ port: 8000 })
Run it with deno run --allow-net middlewares-timer.ts