Skip to content

Grouping Routes

When creating a web server, you would often have multiple routes sharing the same prefix:

typescript
import { 
Elysia
} from 'elysia'
new
Elysia
()
.
post
('/user/sign-in', () => 'Sign in')
.
post
('/user/sign-up', () => 'Sign up')
.
post
('/user/profile', () => 'Profile')
.
listen
(3000)
localhost

POST

This can be improved with Elysia.group, allowing us to apply prefixes to multiple routes at the same time by grouping them together:

typescript
import { 
Elysia
} from 'elysia'
new
Elysia
()
.
group
('/user', (
app
) =>
app
.
post
('/sign-in', () => 'Sign in')
.
post
('/sign-up', () => 'Sign up')
.
post
('/profile', () => 'Profile')
) .
listen
(3000)
localhost

POST

This code behaves the same as our first example and should be structured as follows:

PathResult
/user/sign-inSign in
/user/sign-upSign up
/user/profileProfile

.group() can also accept an optional guard parameter to reduce boilerplate of using groups and guards together:

typescript
import { 
Elysia
,
t
} from 'elysia'
new
Elysia
()
.
group
(
'/user', {
body
:
t
.
Literal
('Rikuhachima Aru')
}, (
app
) =>
app
.
post
('/sign-in', () => 'Sign in')
.
post
('/sign-up', () => 'Sign up')
.
post
('/profile', () => 'Profile')
) .
listen
(3000)

You may find more information about grouped guards in scope.

Prefixing

We can separate a group into a separate plugin instance to reduce nesting by providing a prefix to the constructor.

typescript
import { 
Elysia
} from 'elysia'
const
users
= new
Elysia
({
prefix
: '/user' })
.
post
('/sign-in', () => 'Sign in')
.
post
('/sign-up', () => 'Sign up')
.
post
('/profile', () => 'Profile')
new
Elysia
()
.
use
(
users
)
.
get
('/', () => 'hello world')
.
listen
(3000)
localhost

GET