Integration with SvelteKit
With SvelteKit, you can run Elysia on server routes.
- Create src/routes/[...slugs]/+server.ts.
- In +server.ts, create or import an existing Elysia server
- Export the handler with the name of method you want to expose
typescript
// src/routes/[...slugs]/+server.ts
import { Elysia, t } from 'elysia';
const app = new Elysia()
.get('/', () => 'hello SvelteKit')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
type RequestHandler = (v: { request: Request }) => Response | Promise<Response>
export const GET: RequestHandler = ({ request }) => app.handle(request)
export const POST: RequestHandler = ({ request }) => app.handle(request)
You can treat the Elysia server as a normal SvelteKit server route.
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 with both client-side and server action
Please refer to SvelteKit Routing 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 src/routes/api/[...slugs]/+server.ts, you need to annotate prefix as /api to Elysia server.
typescript
// src/routes/api/[...slugs]/+server.ts
import { Elysia, t } from 'elysia';
const app = new Elysia({ prefix: '/api' })
.get('/', () => 'hi')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
type RequestHandler = (v: { request: Request }) => Response | Promise<Response>
export const GET: RequestHandler = ({ request }) => app.handle(request)
export const POST: RequestHandler = ({ request }) => app.handle(request)
This will ensure that Elysia routing will work properly in any location you place it.