Your First Route
When we enter a website, it takes
- path like
/,/about, or/contact - method like
GET,POST, orDELETE
To determine what a 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'
new Elysia()
.get('/', 'Hello World!')
.listen(3000)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'
new Elysia()
.get('/hello', 'hello')
.get('/hi', 'hi')
.listen(3000)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'
new Elysia()
.get('/id/:id', ({ params: { id } }) => id)
.listen(3000)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'
new Elysia()
.get('/id/:id?', ({ params: { id } }) => `id ${id}`)
.listen(3000)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'
new Elysia()
.get('/id/*', ({ params }) => params['*'])
.listen(3000)See Wildcards.
Assignment
Let's recap, and create 3 paths with different types:
Show answer
- Static path
/elysiathat responds with"Hello Elysia!" - Dynamic path
/friends/:name?that responds with"Hello {name}!" - Wildcard path
/flame-chasers/*that responds with the rest of the path.
import { Elysia } from 'elysia'
new Elysia()
.get('/elysia', 'Hello Elysia!')
.get('/friends/:name?', ({ params: { name } }) => `Hello ${name}!`)
.get('/flame-chasers/*', ({ params }) => params['*'])
.listen(3000)