Skip to content

Handlers ​

Toruk uses native Deno.ServeHandler to handle requests, except parameters come in object shape.

Handler functions receive an object with request and info properties. Expects to return a Response object and can be async functions. Additionaly, you can use Handler type to help you define your handlers.

ts
import type { Handler } from 'https://deno.land/x/toruk/mod.ts'

export const handler: Handler = async function ({ request }) {
  const origin = request.headers.get('origin')

  return new Response(`Hello ${origin}!`)
}

Response ​

Following Deno's best practices, handler functions must return a Response object. This means you should be familiar composing responses using Response API.

ts
// Text response
return new Response('Hello world!')

// JSON response
return Response.json({ hello: 'world' })

// Redirect response
return Response.redirect('/')

💬 Info

For more complex responses like Streams, visit Deno docs.

Parameters ​

Paths are matched using URLPattern object. This allows different patterns, one of them being parameters (named groups). Parameters are strongly typed by default.

ts
import type { Handler } from 'https://deno.land/x/toruk/mod.ts'

export const handler: Handler<'/user/:id'> = async function ({ params }) {
  return new Response(`Hello user Nº ${params.id}!`)
}

Optional parameters ​

Parameters can be optional:

ts
import type { Handler } from 'https://deno.land/x/toruk/mod.ts'

export const handler: Handler<'/user/:id?'> = async function ({ params }) {
  return new Response(`Hello user Nº ${params.id ?? 'no id provided'}!`)
}

Wildcards ​

If you want to ignore part of the path, you can use wildcards pattern *.

ts
import type { Handler } from 'https://deno.land/x/toruk/mod.ts'

export const handler: Handler<'/user/*/name'> = async function () {
  return new Response('Who are you?')
}

RegExp ​

Besides regular expressions are allowed, you might check Regex matchers limitations for edge cases.

ts
import type { Handler } from 'https://deno.land/x/toruk/mod.ts'

// Only matched if `id` is a number, else 404
export const handler: Handler<'/user/:id(\\d+)'> = async function () {
  return new Response(`Hello user Nº ${params.id}!`)
}

Released under the MIT License.