Integration with Nextjs â
With Nextjs App Router, we can run Elysia on Nextjs route.
- Create [[...slugs]]/route.ts inside app router
- In route.ts, create or import an existing Elysia server
- Export the handler with the name of method you want to expose
// app/[[...slugs]]/route.ts
const app = new Elysia()
.get('/', () => 'hello Next')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
export const GET = app.handle
export const POST = app.handle
// app/[[...slugs]]/route.ts
const app = new Elysia()
.get('/', () => 'hello Next')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
export const GET = app.handle
export const POST = app.handle
Elysia will work normally as expected because of WinterCG compliance, however, some plugins like Elysia Static may not work if you are running Nextjs on Node.
You can treat the Elysia server as a normal Nextjs API 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 Nextjs Route Handlers 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 app/api/[[...slugs]]/route.ts, you need to annotate prefix as /api to Elysia server.
// app/api/[[...slugs]]/route.ts
const app = new Elysia({ prefix: '/api' })
.get('/', () => 'hi')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
export const GET = app.handle
export const POST = app.handle
// app/api/[[...slugs]]/route.ts
const app = new Elysia({ prefix: '/api' })
.get('/', () => 'hi')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
export const GET = app.handle
export const POST = app.handle
This will ensure that Elysia routing will work properly in any location you place it.