File system routes for Elysia.js. Inspired by Next.js file system routing.
bun install elysia-autoroutes
Note: It uses your project's /routes
directory as source by default.
import { Elysia } from 'elysia'
import { autoroutes } from 'elysia-autoroutes'
const app = new Elysia()
.use(autoroutes({
routesDir: './routes',
prefix: '/api' // -> optional
}))
.listen(3000)
export type ElysiaApp = typeof app
Create your first route
// routes/index.ts
export async function get() {
return { hello: 'world' }
}
Files inside your project's /routes
directory will get matched a url path automatically.
├── app.ts
├── routes
├── index.ts // index routes
├── posts
├── index.ts
└── [id].ts // dynamic params
└── users.ts
└── package.json
/routes/index.ts
→ //routes/posts/index.ts
→ /posts/routes/posts/[id].ts
→ /posts/:id/routes/users.ts
→ /users
When you export functions like get
, post
, put
, patch
, del
, etc. from a route file, they will be automatically associated with their respective HTTP methods during the matching process.
import type { Context } from 'elysia'
export const get = (context: Context) => ({ ... })
export const post = (context: Context) => ({ ... })
// since it's not allowed to name constants 'delete', try 'del' instead
export const del = (context: Context) => ({ ... })
Convert a function to an object with a handler
and a hooks
property:
import { t } from 'elysia'
export const post = {
handler: ({ body }) => body,
hooks: {
body: t.Object({
username: t.String(),
password: t.String()
})
}
}
Currently, you have the option to export the type of your primary Elysia instance and then import it into your route files.
import type { Context } from 'elysia'
import type { ElysiaApp } from '../app'
export function get({ store }: Context<ElysiaApp['router'], ElysiaApp['store']>) {
return {
version: store.version
}
}
MIT