Your first route
When we enter a website, it takes
- path like
/, /about, or /contact
- method like
GET, POST, or DELETE
To determine which resource to show, simply called “route”.
In Elysia, we can define a route by:
- Call method named after HTTP method
- Path being the first argument
- Handler being the second argument
import { Elysia } from 'elysia'
.get('/', 'Hello World!')
Routing
Path in Elysia can be grouped into 3 types:
- static paths - static string to locate the resource
- dynamic paths - segment can be any value
- wildcards - path until a specific point can be anything
See Route.
Static path
Static path is a hardcoded string to locate the resource on the server.
import { Elysia } from 'elysia'
See Static path.
Dynamic path
Dynamic paths match some part and capture the value to extract extra information.
To define a dynamic path, we can use a colon : followed by a name.
import { Elysia } from 'elysia'
.get('/id/:id', ({ params: { id } }) => id)
Here, a dynamic path is created with /id/:id, which tells Elysia to capture the value :id segment with value like /id/1, /id/123, /id/anything.
See Dynamic path.
Optional path parameters
We can make a path parameter optional by adding a question mark ? after the parameter name.
import { Elysia } from 'elysia'
.get('/id/:id?', ({ params: { id } }) => `id ${id}`)
See Optional path parameters.
Wildcards
Dynamic paths allow capturing a single segment while wildcards allow capturing the rest of the path.
To define a wildcard, we can use an asterisk *.
import { Elysia } from 'elysia'
.get('/id/*', ({ params }) => params['*'])
See Wildcards.
Assignment
Let’s recap, and create 3 paths with different types: