Route - ElysiaJS | ElysiaJS

ID: 2109https://elysiajs.com/essential/route.html
Source

Routing

Web servers use the request’s path and method to look up the correct resource, known as “routing.”
We can define a route with an HTTP verb method, a path, and a function to execute when matched.

import { Elysia } from 'elysia'

new Elysia()
  .get('/', 'hello')
  .get('/hi', 'hi')
  .listen(3000)

You can access the web server by going to http://localhost:3000.
By default, web browsers will send a GET method when visiting a page.


Path type

Path in Elysia can be grouped into three types:

  • static paths – hard‑coded strings to locate the resource
  • dynamic paths – segments that can be any value
  • wildcards – anything after a specific point

You can combine these types to create more powerful routing rules.

import { Elysia } from 'elysia'

new Elysia()
  .get('/id/1', 'static path')
  .get('/id/:id', 'dynamic path')
  .get('/id/*', 'wildcard path')
  .listen(3000)
RouteExample URLs
/id/1/id/1, /id/2, /id/2/a
/id/*/id/anything, /id/anything/test

Static Path

A static path is a hard‑coded string to locate a resource on the server.

import { Elysia } from 'elysia'

new Elysia()
  .get('/hello', 'hello')
  .get('/hi', 'hi')
  .listen(3000)

Dynamic Path

Dynamic paths match a part of the URL and capture that value for later use.
To define a dynamic path, prefix a segment with a colon (:) followed by a name.

import { Elysia } from 'elysia'

new Elysia()
  .get('/id/:id', ({ params: { id } }) => id)
  .listen(3000)

When requested, the server will return:

PathResponse
/id/11
/id/123123
/id/anythinganything
/id/anything?name=saltanything
/idNot Found
/id/anything/restNot Found

The named variable path is referred to as a path parameter or simply params.

Multiple path parameters

You can have as many path parameters as you like; they are stored in a params object.

import { Elysia } from 'elysia'

new Elysia()
  .get('/id/:id', ({ params: { id } }) => id)
  .get('/id/:id/:name', ({ params: { id, name } }) => `${id}/${name}`)
  .listen(3000)

For example:

  • /id/5 returns 5
  • /id/5/alice returns 5/alice

Tips

Using the interactive browser above, hover on the highlighted area to see different results between each path.