Integration with Astro
With Astro Endpoint, we can run Elysia on Astro directly.
- Set output to server in astro.config.mjs
// astro.config.mjs
import { defineConfig } from 'astro/config'
// https://astro.build/config
export default defineConfig({
output: 'server'
})
- Create pages/[...slugs].ts
- Create or import an existing Elysia server in [...slugs].ts
- Export the handler with the name of method you want to expose
// pages/[...slugs].ts
import { Elysia, t } from 'elysia'
const app = new Elysia()
.get('/api', () => 'hi')
.post('/api', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
const handle = ({ request }: { request: Request }) => app.handle(request)
export const GET = handle
export const POST = handle
Elysia will work normally as expected because of WinterCG compliance.
We recommended running Astro on Bun as Elysia is designed to be run on Bun
TIP
You can run Elysia server without running Astro on Bun thanks to WinterCG support.
However some plugins like Elysia Static may not work if you are running Astro on Node.
With this approach, you can have co-location of both frontend and backend in a single repository and have End-to-end type-safety with Eden.
Please refer to Astro Endpoint for more information.
Prefix
If you place an Elysia server not in the root directory of the app router, you need to annotate the prefix to the Elysia server.
For example, if you place Elysia server in pages/api/[...slugs].ts, you need to annotate prefix as /api to Elysia server.
// pages/api/[...slugs].ts
import { Elysia, t } from 'elysia'
const app = new Elysia({ prefix: '/api' })
.get('/', () => 'hi')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
const handle = ({ request }: { request: Request }) => app.handle(request)
export const GET = handle
export const POST = handle
This will ensure that Elysia routing will work properly in any location you place it.