integrations/nextjs #613
Replies: 11 comments 14 replies
-
|
Well... this is fun... blackfyre …/trusted-payments/trusted-payments main ✘!? v22.17.0 20:13
bun dev
$ next dev --turbopack
▲ Next.js 15.5.2 (Turbopack)
- Local: http://localhost:3000
- Network: http://192.168.0.190:3000
✓ Starting...
✓ Ready in 702ms
○ Compiling /api/[[...slugs]] ...
✓ Compiled /api/[[...slugs]] in 1489ms
⨯ Detected default export in '[project]/src/app/api/[[...slugs]]/route.ts'. Export a named export for each HTTP method instead.
⨯ No HTTP methods exported in '[project]/src/app/api/[[...slugs]]/route.ts'. Export a named export for each HTTP method.
⨯ Detected default export in '[project]/src/app/api/[[...slugs]]/route.ts'. Export a named export for each HTTP method instead.
⨯ No HTTP methods exported in '[project]/src/app/api/[[...slugs]]/route.ts'. Export a named export for each HTTP method.
GET /api 405 in 2286msFollowed the description here. |
Beta Was this translation helpful? Give feedback.
-
|
for nextjs 16 seems there some changes. notice this. import { Elysia, t } from 'elysia'
import { swagger } from '@elysiajs/swagger'
const app = new Elysia({ prefix: '/api' })
.use(
swagger({
documentation: {
info: {
title: 'Next.js + Elysia API',
version: '1.0.0',
description: 'Type-safe API built with Elysia.js and Next.js',
},
tags: [
{ name: 'General', description: 'General endpoints' },
{ name: 'Users', description: 'User management endpoints' },
{ name: 'Posts', description: 'Post management endpoints' },
],
},
})
)
.get('/', () => 'Hello from Elysia!', {
detail: {
tags: ['General'],
summary: 'Root endpoint',
description: 'Returns a simple greeting message',
},
})
.get(
'/health',
() => ({
status: 'ok',
timestamp: new Date().toISOString(),
}),
{
detail: {
tags: ['General'],
summary: 'Health check',
description: 'Returns the API health status and current timestamp',
},
}
)
.get(
'/users/:id',
({ params: { id } }) => ({
id,
name: `User ${id}`,
}),
{
detail: {
tags: ['Users'],
summary: 'Get user by ID',
description: 'Retrieves a user by their unique identifier',
},
params: t.Object({
id: t.String({ description: 'User ID' }),
}),
}
)
.post(
'/users',
({ body }) => ({
success: true,
user: body,
}),
{
detail: {
tags: ['Users'],
summary: 'Create a new user',
description: 'Creates a new user with the provided information',
},
body: t.Object({
name: t.String({ description: 'User full name' }),
email: t.String({ description: 'User email address', format: 'email' }),
}),
}
)
.get(
'/posts',
({ query }) => ({
posts: [
{ id: 1, title: 'First Post' },
{ id: 2, title: 'Second Post' },
],
page: query.page || 1,
}),
{
detail: {
tags: ['Posts'],
summary: 'Get all posts',
description: 'Retrieves a paginated list of posts',
},
query: t.Object({
page: t.Optional(t.Number({ description: 'Page number for pagination' })),
}),
}
)
// Export type for Eden Treaty
export type App = typeof app
// Export HTTP method handlers
export const GET = app.handle
export const POST = app.handle
export const PUT = app.handle
export const DELETE = app.handle
export const PATCH = app.handle |
Beta Was this translation helpful? Give feedback.
-
|
this is the best way to handle errors in nextjs: see: elysia-next-error-handler import { Elysia, NotFoundError } from "elysia";
import { APIError } from "@/lib/api-error";
import { notFound } from "next/navigation";
const app = new Elysia({ prefix: "/api" })
.onError(({ error, set }) => {
if (error instanceof APIError) {
set.status = error.status;
return {
success: false,
message: error.message,
code: error.code,
};
} else if (error instanceof NotFoundError) {
notFound();
} else if (isNextJsInternalError(error)) {
throw error;
}
// Log the actual error for debugging
console.error("Internal Server Error:", error);
set.status = 500;
return {
success: false,
message: "Internal Server Error",
};
})function isNextJsInternalError(error: unknown): boolean {
if (typeof error !== "object" || error === null || !("digest" in error)) {
return false;
}
const digest = (error as { digest?: string }).digest;
// Checks for NEXT_REDIRECT, NEXT_NOT_FOUND, etc.
return typeof digest === "string" && digest.startsWith("NEXT_");
}// lib/api-error.ts
export class APIError extends Error {
constructor(
public message: string,
public status: number = 500,
public code?: string
) {
super(message);
}
} |
Beta Was this translation helpful? Give feedback.
-
|
As of 13-12-2025, thank you for adding the isomorphic fetch pattern. This enables ISR on NextJS powered by Elysia. 🙏 |
Beta Was this translation helpful? Give feedback.
-
|
Is type safety achievable on standalone Elysia backend server running on a port? |
Beta Was this translation helpful? Give feedback.
-
|
shouldn't it be instead |
Beta Was this translation helpful? Give feedback.
-
|
When using it with Next, it seems to instantiate Elysia in every API call, making the database connections being rebuilt in every call. Anyone knows how to make them persistent? import Elysia from "elysia";
import { fromTypes, openapi } from "@elysiajs/openapi";
import * as routes from "@src/routes"; // These routes use database connections
import { Logger } from "@src/lib/logger"; // In logs I see that every API call logs that the connections are being connected again.
const app = new Elysia({
prefix: "/api",
})
.use(openapi())
.use(routes.categories)
.use(routes.comandas)
.use(routes.items)
.use(routes.restaurants)
.use(routes.images)
.use(routes.orders)
.use(routes.serviceAccounts)
.use(routes.sessions)
.use(routes.users)
.use(routes.analytics)
export const GET = app.fetch
export const POST = app.fetch
export const HEAD = app.fetch
export const PUT = app.fetch
export const DELETE = app.fetch
export const OPTIONS = app.fetch |
Beta Was this translation helpful? Give feedback.
-
|
export const api =
typeof process !== 'undefined'
? treaty(app).api
: treaty<typeof app>('localhost:3000').api |
Beta Was this translation helpful? Give feedback.
-
|
I'm not getting linter errors in this code: import { Elysia, t } from "elysia"; export const app = new Elysia({ prefix: "/api" }) export const GET = app.fetch; // Exporta el tipo de la app para Eden Treaty - CRÍTICO para type safety export default async function Home() { const response = await api.post({ console.log({ response }); return ( {JSON.stringify(data)} Response: {JSON.stringify(response.data)} {response.error && ( <div style={{ color: "red" }}> Error {response.error.status}:{" "} {JSON.stringify(response.error.value.property)} {JSON.stringify(response.error.value.message)} )} </> ); } this should give me a linter error am i right?? |
Beta Was this translation helpful? Give feedback.
-
|
I use the following without problems import { type Treaty, treaty } from "@elysiajs/eden";
import { app } from "@/app/api/[[...apiRoutes]]/route";
// .api to enter /api prefix
export const api = typeof window !== "undefined" ? treaty<typeof app>(window.location.origin).api : treaty(app).api; |
Beta Was this translation helpful? Give feedback.
-
|
If I want to run Elysia on the Node.js runtime instead of Bun, do I need to use the Node adapter? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
integrations/nextjs
With Next.js App Router, you can run Elysia on Next.js routes. Elysia will work normally as expected because of WinterCG compliance.
https://elysiajs.com/integrations/nextjs.html
Beta Was this translation helpful? Give feedback.
All reactions