Skip to content

与 Next.js 集成

¥Integration with Next.js

使用 Next.js App Router,我们可以在 Next.js 路由上运行 Elysia。

¥With Next.js App Router, we can run Elysia on Next.js routes.

  1. 在应用路由内创建 api/[[...slugs]]/route.ts
  2. 在 route.ts 中,创建或导入现有的 Elysia 服务器。
  3. 将 Elysia 服务器导出为默认导出
typescript
// app/api/[[...slugs]]/route.ts
import { Elysia, t } from 'elysia'

export default new Elysia({ prefix: '/api' })
    .get('/', () => 'hello Next')
    .post('/', ({ body }) => body, {
        body: t.Object({
            name: t.String()
        })
    })

由于符合 WinterCG 标准,Elysia 将按预期正常工作,但是,如果你在 Node 上运行 Next.js,某些插件(例如 Elysia Static)可能无法正常工作。

¥Elysia will work normally as expected because of WinterCG compliance, however, some plugins like Elysia Static may not work if you are running Next.js on Node.

你可以将 Elysia 服务器视为普通的 Next.js API 路由。

¥You can treat the Elysia server as a normal Next.js API route.

通过这种方法,你可以将前端和后端共存于一个存储库中,并且 使用 Eden 实现端到端类型安全 可以同时执行客户端和服务器操作。

¥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

更多信息请参阅 Next.js 路由处理程序

¥Please refer to Next.js Route Handlers for more information.

前缀

¥Prefix

由于我们的 Elysia 服务器不在应用路由的根目录中,因此需要将前缀注释到 Elysia 服务器。

¥Because our Elysia server is not in the root directory of the app router, you need to annotate the prefix to the Elysia server.

例如,如果你将 Elysia 服务器放置在 app/user/[[...slugs]]/route.ts 中,则需要将 Elysia 服务器的前缀注释为 /user。

¥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/user/[[...slugs]]/route.ts
import { Elysia, t } from 'elysia'

export default new Elysia({ prefix: '/user' }) 
    .get('/', () => 'hi')
    .post('/', ({ body }) => body, {
        body: t.Object({
            name: t.String()
        })
    })

这将确保 Elysia 路由在你放置它的任何位置都能正常工作。

¥This will ensure that Elysia routing will work properly in any location you place it.