Skip to content

Integration with Nextjs

With Nextjs App Router, we can run Elysia on Nextjs route.

  1. Create api/[[...slugs]]/route.ts inside app router
  2. In route.ts, create or import an existing Elysia server
  3. Export the handler with the name of method you want to expose
typescript
// app/[[...slugs]]/route.ts
import { 
Elysia
,
t
} from 'elysia'
const
app
= new
Elysia
({
prefix
: '/api' })
.
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

Because our Elysia server is 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/user/[[...slugs]]/route.ts, you need to annotate prefix as /user to Elysia server.

typescript
// app/api/[[...slugs]]/route.ts
import { 
Elysia
,
t
} from 'elysia'
const
app
= new
Elysia
({
prefix
: '/user' })
.
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.