### Basic Elysia Server Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Sets up a minimal Elysia server with a single GET route and logs the server details.
```typescript
import { Elysia } from 'elysia'
const app = new Elysia()
.get('/', () => 'Hello Elysia')
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
```
--------------------------------
### ElysiaJS Hello World Example
Source: https://github.com/elysiajs/documentation/blob/main/docs/at-glance.md
A basic ElysiaJS application demonstrating GET and POST routes, and parameter handling. This snippet requires Elysia to be imported and the server to be started on port 3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'Hello Elysia')
.get('/user/:id', ({ params: { id } }) => id)
.post('/form', ({ body }) => body)
.listen(3000)
```
--------------------------------
### Install Server Timing Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/server-timing.md
Install the plugin using bun.
```bash
bun add @elysia/server-timing
```
--------------------------------
### Basic Trace Listener Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/trace.md
Set up a basic trace listener to hook into the 'onBeforeHandle' lifecycle event. This example demonstrates how to initialize the listener and log information within it.
```typescript
import { Elysia } from 'elysia'
const app = new Elysia()
.trace(({ onBeforeHandle }) => {
// This is trace listener
// hover to view the type
onBeforeHandle((parameter) => {
})
})
.get('/', () => 'Hi')
.listen(3000)
```
--------------------------------
### Install Elysia Static Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/static.md
Install the @elysiajs/static plugin using Bun.
```bash
bun add @elysia/static
```
--------------------------------
### Define Basic Routes with GET Method
Source: https://github.com/elysiajs/documentation/blob/main/docs/essential/route.md
Define routes using Elysia.get for handling GET requests. This example shows how to map different paths to simple string responses.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'hello')
.get('/hi', 'hi')
.listen(3000)
```
--------------------------------
### Install Cron Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/cron.md
Install the @elysia/cron plugin using bun.
```bash
bun add @elysia/cron
```
--------------------------------
### Install JWT Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/jwt.md
Install the JWT plugin using bun.
```bash
bun add @elysia/jwt
```
--------------------------------
### Apply OpenTelemetry Plugin to Elysia Instance
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/opentelemetry.md
Install the plugin using 'bun add @elysia/opentelemetry' and apply it to your Elysia instance. This example shows basic setup with default OTLP exporter and BatchSpanProcessor.
```typescript
import { Elysia } from 'elysia'
import { opentelemetry } from '@elysia/opentelemetry'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
new Elysia()
.use(
opentelemetry({
spanProcessors: [
new BatchSpanProcessor(
new OTLPTraceExporter()
)
]
})
)
```
--------------------------------
### Install OpenAPI Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/openapi.md
Install the OpenAPI plugin using bun. This is the first step to enable automatic API documentation generation.
```bash
bun add @elysia/openapi
```
--------------------------------
### Install Prisma and Prismabox
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/prisma.md
Install the necessary packages for Prisma, Prismabox, and the Bun SQLite adapter. Use the -d flag for development dependencies.
```bash
bun add @prisma/client prismabox prisma-adapter-bun-sqlite && \
bun add -d prisma
```
--------------------------------
### Unit Test Elysia Application with Vitest
Source: https://github.com/elysiajs/documentation/blob/main/docs/tutorial/features/unit-test/index.md
Illustrates how to unit test an Elysia application using Vitest. The example defines an Elysia instance, simulates a GET request to the root path using `app.fetch`, and verifies that the response body is 'Hello World'. This approach facilitates testing without the need for a live server.
```typescript
import { describe, it, expect } from 'vitest'
import { Elysia } from 'elysia'
describe('Elysia', () => {
it('should return Hello World', async () => {
const app = new Elysia().get('/', 'Hello World')
const text = await app.fetch(new Request('http://localhost/'))
.then(res => res.text())
expect(text).toBe('Hello World')
})
})
```
--------------------------------
### Install nuxt-elysia and dependencies
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/nuxt.md
Install the 'nuxt-elysia' plugin and necessary Elysia dependencies using bun.
```bash
bun add elysia @elysia/eden
bun add -d nuxt-elysia
```
--------------------------------
### Create a Basic Route
Source: https://github.com/elysiajs/documentation/blob/main/docs/tutorial/getting-started/your-first-route/index.md
Defines a simple GET route at the root path that responds with 'Hello World!'. Requires Elysia to be imported and the server to be started on port 3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'Hello World!')
.listen(3000)
```
--------------------------------
### Basic Elysia GraphQL Yoga Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/graphql-yoga.md
Integrate GraphQL Yoga with Elysia by using the plugin. This example sets up a basic GraphQL schema with a 'hi' query.
```typescript
import { Elysia } from 'elysia'
import { yoga } from '@elysia/graphql-yoga'
const app = new Elysia()
.use(
yoga({
typeDefs: /* GraphQL */ `
type Query {
hi: String
}
`,
resolvers: {
Query: {
hi: () => 'Hello from Elysia'
}
}
})
)
.listen(3000)
```
--------------------------------
### Install Eden and Elysia
Source: https://github.com/elysiajs/documentation/blob/main/docs/eden/installation.md
Install Eden and Elysia on your frontend project using Bun. Ensure Elysia is installed to allow Eden to infer utility types.
```bash
bun add @elysia/eden
bun add -d elysia
```
--------------------------------
### Install Apollo GraphQL Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/graphql-apollo.md
Install the necessary packages for the Apollo GraphQL plugin using bun.
```bash
bun add graphql @elysia/apollo @apollo/server
```
--------------------------------
### Install Bun on Windows
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Bun using a PowerShell command for Windows systems.
```powershell
powershell -c "irm bun.sh/install.ps1 | iex"
```
--------------------------------
### Install Elysia with bun (Web Standard)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia using bun for environments that support Web Standard Request/Response.
```bash
bun install elysia
```
--------------------------------
### Vue Component Setup with Imports
Source: https://github.com/elysiajs/documentation/blob/main/docs/migrate/index.txt
Standard Vue.js setup for importing components. Ensure components are correctly located in the specified paths.
```vue
```
--------------------------------
### Install Elysia Node Adapter
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/node.md
Install the Elysia core package and the Node.js adapter using your preferred package manager.
```bash
bun add elysia @elysia/node
```
```bash
pnpm add elysia @elysia/node
```
```bash
npm install elysia @elysia/node
```
```bash
yarn add elysia @elysia/node
```
--------------------------------
### Install Node.js on Windows
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Node.js using Chocolatey package manager on Windows.
```powershell
choco install nodejs
```
--------------------------------
### Install Bun on MacOS/Linux
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Bun using a curl command for MacOS and Linux systems.
```bash
curl -fsSL https://bun.sh/install | bash
```
--------------------------------
### Install Elysia HTML Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/html.md
Install the Elysia HTML plugin using Bun package manager.
```bash
bun add @elysia/html
```
--------------------------------
### Install and Use OpenTelemetry Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/opentelemetry.md
Install the plugin using 'bun add @elysia/opentelemetry' and apply it to your Elysia instance with a single line of configuration.
```typescript
import { Elysia } from 'elysia'
import { opentelemetry } from '@elysia/opentelemetry'
new Elysia()
.use(opentelemetry())
```
--------------------------------
### Install Elysia with bun (JavaScript)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia and the Node.js adapter using the bun package manager for a JavaScript project.
```bash
bun add elysia @elysia/node
```
--------------------------------
### Install Elysia with yarn (Web Standard)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia using yarn for environments that support Web Standard Request/Response.
```bash
yarn add elysia
```
--------------------------------
### Install Elysia with npm (JavaScript)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia and the Node.js adapter using npm for a JavaScript project.
```bash
npm install elysia @elysia/node
```
--------------------------------
### Install Elysia with pnpm (Web Standard)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia using pnpm for environments that support Web Standard Request/Response. Note that pnpm may not install peer dependencies automatically.
```bash
pnpm install elysia @sinclair/typebox openapi-types
```
--------------------------------
### Install Elysia with yarn (JavaScript)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia and the Node.js adapter using yarn for a JavaScript project.
```bash
yarn add elysia @elysia/node
```
--------------------------------
### Start Elysia Development Server
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Starts the Elysia development server, which automatically reloads on file changes.
```bash
bun dev
```
--------------------------------
### Install Node.js on Arch Linux
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Node.js and npm using the pacman package manager on Arch Linux.
```bash
pacman -S nodejs npm
```
--------------------------------
### Install Elysia Swagger Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/with-prisma.md
Installs the necessary Elysia Swagger plugin using Bun. This is a prerequisite for generating API documentation.
```bash
bun add @elysiajs/swagger
```
--------------------------------
### Install GraphQL Yoga Plugin
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/graphql-yoga.md
Install the plugin using npm or yarn. This is the first step to integrating GraphQL Yoga with Elysia.
```bash
bun add @elysia/graphql-yoga
```
--------------------------------
### Install Elysia with npm (Web Standard)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia using npm for environments that support Web Standard Request/Response.
```bash
npm install elysia
```
--------------------------------
### Install Elysia with PNPM for Node.js
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia and its Node.js adapter using PNPM, along with development dependencies.
```bash
pnpm add elysia @elysia/node
pnpm add -D tsx @types/node typescript
```
--------------------------------
### Install Prisma CLI
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/with-prisma.md
Installs the Prisma CLI as a development dependency. This tool is used for database schema management and migrations.
```bash
bun add -d prisma
```
--------------------------------
### Monorepo Dockerfile Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/deploy.md
Configure a Dockerfile within an application's directory in a monorepo structure to build and compile your ElysiaJS application. This example assumes a Turborepo setup.
```dockerfile
FROM oven/bun:1 AS build
WORKDIR /app
# Cache packages
COPY package.json package.json
COPY bun.lock bun.lock
COPY /apps/server/package.json ./apps/server/package.json
COPY /packages/config/package.json ./packages/config/package.json
RUN bun install
COPY /apps/server ./apps/server
COPY /packages/config ./packages/config
ENV NODE_ENV=production
RUN bun build \
--compile \
--minify-whitespace \
--minify-syntax \
--outfile server \
src/index.ts
FROM gcr.io/distroless/base
WORKDIR /app
COPY --from=build /app/server server
ENV NODE_ENV=production
CMD ["./server"]
EXPOSE 3000
```
--------------------------------
### Install Elysia with yarn
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Use this command to install Elysia and @elysia/node with yarn, along with development dependencies tsx, @types/node, and typescript.
```bash
yarn add elysia @elysia/node && \
```
```bash
yarn add -D tsx @types/node typescript
```
--------------------------------
### Install Elysia with npm
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Use this command to install Elysia and @elysia/node with npm, along with development dependencies tsx, @types/node, and typescript.
```bash
npm install elysia @elysia/node && \
```
```bash
npm install --save-dev tsx @types/node typescript
```
--------------------------------
### Plugin with State and Route (Demo 2)
Source: https://github.com/elysiajs/documentation/blob/main/docs/essential/plugin.md
This demonstrates using a plugin that sets up state and a route. It's similar to the first plugin example but shows a different usage context.
```typescript
const _demo2 = new Elysia()
.use(plugin2)
.get('/parent', () => 'parent')
```
--------------------------------
### Basic Elysia OpenTelemetry Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/elysia-11.md
Demonstrates the basic setup for integrating OpenTelemetry into an Elysia application. It requires installing the `@elysiajs/opentelemetry` package and applying the plugin to an Elysia instance. This configuration uses a BatchSpanProcessor and an OTLPTraceExporter.
```typescript
import { Elysia } from 'elysia'
import { opentelemetry } from '@elysiajs/opentelemetry'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
new Elysia()
.use(
opentelemetry({
spanProcessors: [
new BatchSpanProcessor(
new OTLPTraceExporter()
)
]
})
)
```
--------------------------------
### GET /user with Response Validation
Source: https://github.com/elysiajs/documentation/blob/main/docs/tutorial/getting-started/validation/index.md
This example illustrates how to define validation schemas for different response status codes for a GET request to the `/user` endpoint. Elysia validates the response before sending it and provides type inference.
```APIDOC
## GET /user
### Description
Defines response validation schemas for status codes 200 and 418 for the `/user` endpoint. Elysia ensures the response conforms to the specified types.
### Method
GET
### Endpoint
/user
### Response
#### Success Response (200)
- **string** - A literal string 'Hello Elysia!'.
#### Response Example (200)
```
Hello Elysia!
```
#### Success Response (418)
- **object** - An object with a 'message' field, which must be the literal string "I'm a teapot".
#### Response Example (418)
```json
{
"message": "I'm a teapot"
}
```
```
--------------------------------
### Express OpenAPI Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/migrate/from-express.txt
Demonstrates setting up OpenAPI documentation in Express using swagger-ui-express. Requires separate configuration for validation and type safety.
```typescript
import express from 'express'
import swaggerUi from 'swagger-ui-express'
const app = express()
app.use(express.json())
app.post('/users', (req, res) => {
// TODO: validate request body
res.status(201).json(req.body)
})
const swaggerSpec = {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0'
},
paths: {
'/users': {
post: {
summary: 'Create user',
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'First name only'
},
age: { type: 'integer' }
},
required: ['name', 'age']
}
}
}
},
responses: {
'201': {
description: 'User created'
}
}
}
}
}
}
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec))
```
--------------------------------
### Eden Treaty Example - Elysia Server
Source: https://github.com/elysiajs/documentation/blob/main/docs/eden/overview.md
Defines an Elysia server with multiple routes, including a GET route, a POST route with a typed body, and a parameterized GET route. This server definition is used for type inference with Eden Treaty.
```typescript
// @filename: server.ts
import { Elysia, t } from 'elysia'
const app = new Elysia()
.get('/', 'hi')
.get('/users', () => 'Skadi')
.put('/nendoroid/:id', ({ body }) => body, {
body: t.Object({
name: t.String(),
from: t.String()
})
})
.get('/nendoroid/:id/name', () => 'Skadi')
.listen(3000)
export type App = typeof app
```
--------------------------------
### Basic Better Auth Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/better-auth.md
Initializes a Better Auth instance with a PostgreSQL database pool.
```typescript
import { betterAuth } from 'better-auth'
import { Pool } from 'pg'
export const auth = betterAuth({
database: new Pool()
})
```
--------------------------------
### Basic ElysiaJS Server Setup
Source: https://github.com/elysiajs/documentation/blob/main/docs/index.md
Demonstrates a simple ElysiaJS server with basic routing for text, static files, streaming responses, and WebSocket communication.
```typescript
import { Elysia, file } from 'elysia'
new Elysia()
.get('/', 'Hello World')
.get('/image', file('mika.webp'))
.get('/stream', function* () {
yield 'Hello'
yield 'World'
})
.ws('/realtime', {
message(ws, message) {
ws.send('got:' + message)
}
})
.listen(3000)
```
--------------------------------
### Define and Validate Path Parameters in ElysiaJS
Source: https://github.com/elysiajs/documentation/blob/main/docs/essential/validation.md
This example shows how to define and validate a numeric path parameter 'id' for a GET request.
```typescript
import { Elysia, t } from 'elysia'
new Elysia()
.get('/id/:id', ({ params }) => params, {
params: t.Object({
id: t.Number()
})
})
```
--------------------------------
### Simulate Network Request with Fastify
Source: https://github.com/elysiajs/documentation/blob/main/docs/migrate/from-fastify.txt
Fastify uses `fastify.inject()` to simulate network requests for testing. This example demonstrates a basic GET request test.
```typescript
import fastify from 'fastify'
import request from 'supertest'
import { describe, it, expect } from 'vitest'
function build(opts = {}) {
const app = fastify(opts)
app.get('/', async function (request, reply) {
reply.send({ hello: 'world' })
})
return app
}
describe('GET /', () => {
it('should return Hello World', async () => {
const app = build()
const response = await app.inject({
url: '/',
method: 'GET',
})
expect(res.status).toBe(200)
expect(res.text).toBe('Hello World')
})
})
```
--------------------------------
### Use decorated properties with prefix
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/extends-context.md
This example demonstrates using a decorated Elysia instance ('setup') with a prefix and accessing its decorated properties in a new handler.
```typescript
import {
Elysia
} from 'elysia'
const setup = new Elysia({ name: 'setup' })
.decorate({
argon: 'a',
boron: 'b',
carbon: 'c'
})
const demo5 = new Elysia()
.use(
setup
.prefix('decorator', 'setup')
)
.get('/', ({ setupCarbon }) => setupCarbon)
```
--------------------------------
### End-to-End Type-Safe Testing with Elysia Eden
Source: https://github.com/elysiajs/documentation/blob/main/docs/migrate/from-fastify.txt
Elysia's Eden library provides end-to-end type-safe testing with auto-completion. This example tests a GET request.
```typescript
import { Elysia } from 'elysia'
import { treaty } from '@elysia/eden'
import { describe, it, expect } from 'bun:test'
const app = new Elysia().get('/hello', 'Hello World')
const api = treaty(app)
describe('GET /', () => {
it('should return Hello World', async () => {
const { data, error, status } = await api.hello.get()
expect(status).toBe(200)
expect(data).toBe('Hello World')
})
})
```
--------------------------------
### Initialize Prisma Project
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/with-prisma.md
Initializes a new Prisma project within your existing directory. This generates essential configuration files like schema.prisma and .env.
```bash
bunx prisma init
```
--------------------------------
### Elysia Instance Hook Encapsulation Example (TypeScript)
Source: https://github.com/elysiajs/documentation/blob/main/docs/tutorial/getting-started/encapsulation/index.md
Demonstrates how Elysia hooks are encapsulated within their own instance. Creating a new instance with `.use()` does not share hooks unless explicitly scoped. This example shows a basic setup where hooks are local to the instance they are defined in.
```typescript
import { Elysia } from 'elysia'
const profile = new Elysia()
.onBeforeHandle(
({ query: { name }, status }) => {
if(!name)
return status(401)
}
)
.get('/profile', () => 'Hi!')
new Elysia()
.use(profile)
.patch('/rename', () => 'Ok! XD')
.listen(3000)
```
--------------------------------
### Define Routes in Hono
Source: https://github.com/elysiajs/documentation/blob/main/docs/migrate/from-hono.txt
Hono uses helper methods like `c.text` and `c.json` to return responses. This example shows basic GET and POST route definitions.
```typescript
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => {
return c.text('Hello World')
})
app.post('/id/:id', (c) => {
c.status(201)
return c.text(req.params.id)
})
export default app
```
--------------------------------
### WebSocket Basic Usage
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/websocket.md
This example demonstrates the basic setup for a WebSocket endpoint in Elysia. It listens for messages on the '/ws' path and echoes them back to the client.
```APIDOC
## POST /ws
### Description
Sets up a WebSocket endpoint that echoes received messages back to the client.
### Method
WS
### Endpoint
/ws
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None (WebSocket messages are handled differently)
### Request Example
```
(Client sends a message)
```
### Response
#### Success Response (200)
- **message** (string) - The message echoed back to the client.
#### Response Example
```json
{
"message": "Hello from server!"
}
```
```
--------------------------------
### tRPC Server Setup and Routing
Source: https://github.com/elysiajs/documentation/blob/main/docs/migrate/from-trpc.txt
Demonstrates setting up a tRPC server with nested routers and procedures for defining queries and mutations. Requires @trpc/server and @trpc/server/adapters/standalone.
```typescript
import { initTRPC } from '@trpc/server'
import { createHTTPServer } from '@trpc/server/adapters/standalone'
const t = initTRPC.create()
const appRouter = t.router({
hello: t.procedure.query(() => 'Hello World'),
user: t.router({
getById: t.procedure
.input((id: string) => id)
.query(({ input }) => {
return { id: input }
})
})
})
const server = createHTTPServer({
router: appRouter
})
server.listen(3000)
```
--------------------------------
### Setup PostgreSQL Database with Docker
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/with-prisma.md
Command to run a PostgreSQL database instance using Docker. This is a convenient way to set up a database for development purposes.
```bash
docker run -p 5432:5432 -e POSTGRES_PASSWORD=12345678 -d postgres
```
--------------------------------
### Install Bun Type Definitions
Source: https://github.com/elysiajs/documentation/blob/main/docs/eden/installation.md
If using Bun-specific features in your handlers, install the Bun type definitions to ensure proper type checking on the client.
```bash
bun add -d @types/bun
```
--------------------------------
### Elysia Route Registration Example
Source: https://github.com/elysiajs/documentation/blob/main/docs/internal/jit-compiler.md
A basic Elysia application setup demonstrating how a route is registered. The JIT compiler and Sucrose analyze this code to determine which parts of the request are necessary for the handler.
```typescript
import { Elysia } from 'elysia'
const app = new Elysia()
.patch('/user/:id', ({ params }) => {
return { id: req.params.id }
})
```
--------------------------------
### ElysiaJS Type Inference Example
Source: https://github.com/elysiajs/documentation/blob/main/docs/at-glance.md
Demonstrates ElysiaJS's automatic type inference for route parameters. The 'id' parameter is typed automatically without explicit TypeScript declarations. This code requires Elysia to be imported and the server to be started on port 3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/user/:id', ({ params: { id } }) => id)
// ^?
.listen(3000)
```
--------------------------------
### Define Elysia Server for Expo API Route
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/expo.md
Create an Elysia server and export its fetch method for GET and POST requests in an Expo API route. Ensure necessary peer dependencies like @sinclair/typebox and openapi-types are installed if using pnpm.
```typescript
import { Elysia, t } from 'elysia'
const app = new Elysia()
.get('/', 'hello Expo')
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String()
})
})
export const GET = app.fetch
export const POST = app.fetch
```
--------------------------------
### Create a Custom GraphQL Server
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/cheat-sheet.md
Shows how to set up a GraphQL server using the @elysiajs/graphql-yoga plugin, including defining types and resolvers.
```typescript
import { Elysia } from 'elysia'
import { yoga } from '@elysiajs/graphql-yoga'
const app = new Elysia()
.use(
yoga({
typeDefs: /* GraphQL */`
type Query {
hi: String
}
`,
resolvers: {
Query: {
hi: () => 'Hello from Elysia'
}
}
})
)
.listen(3000)
```
--------------------------------
### Eden Treaty Example - Client Usage
Source: https://github.com/elysiajs/documentation/blob/main/docs/eden/overview.md
Demonstrates how to use Eden Treaty to connect to an Elysia server and interact with its routes. It shows type-safe calls for GET and PUT requests, including parameter and body handling. Requires the server definition to be imported.
```typescript
// @filename: index.ts
// ---cut---
import { treaty } from '@elysia/eden'
import type { App } from './server'
const app = treaty('localhost:3000')
// @noErrors
app.
// ^|
```
```typescript
// Call [GET] at '/'
const { data } = await app.get()
```
```typescript
// Call [PUT] at '/nendoroid/:id'
const { data: nendoroid, error } = await app.nendoroid({ id: 1895 }).put({
name: 'Skadi',
from: 'Arknights'
})
```
--------------------------------
### Add Swagger Documentation Plugin to ElysiaJS
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/elysia-supabase.md
This example demonstrates how to add the `@elysiajs/swagger` plugin to an ElysiaJS application. After installing the plugin via Bun, it's imported and used with the `app.use()` method. This automatically generates interactive API documentation based on the defined routes and schemas.
```typescript
import { Elysia, t } from 'elysia'
import { swagger } from '@elysiajs/swagger'
import { auth, post } from './modules'
const app = new Elysia()
.use(swagger())
.use(auth)
.use(post)
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
```
--------------------------------
### Build Fullstack Server for Production
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/fullstack-dev-server.md
Compile your fullstack Bun server into a single executable file using the 'bun build' command. Ensure the target is 'bun' and specify an outfile.
```bash
bun build --compile --target bun --outfile server src/index.ts
```
--------------------------------
### Run Netlify Development Environment (Bash)
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/netlify.md
This command starts the Netlify development environment, which simulates Netlify hosting and Edge Functions locally. It allows you to test your Elysia application integrated with Netlify Edge Functions in a local development setup.
```bash
netlify dev
```
--------------------------------
### Modify Server Response in Elysia
Source: https://github.com/elysiajs/documentation/blob/main/docs/tutorial/index.md
This snippet demonstrates how to change the response of a GET request in an Elysia application. It shows the specific line of code to modify within the `.get` method to alter the server's output from 'Hello World!' to 'Hello Elysia!'. This is a fundamental example for beginners learning Elysia.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'Hello World!') // [!code --]
.get('/', 'Hello Elysia!') // [!code ++]
.listen(3000)
```
--------------------------------
### Install Production Dependencies
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/deploy.md
Install only the production dependencies on your server after deploying your bundled application or binary. This ensures that only necessary packages are present, optimizing runtime.
```bash
bun install --production
```
--------------------------------
### Install Elysia with pnpm (JavaScript)
Source: https://github.com/elysiajs/documentation/blob/main/docs/quick-start.md
Installs Elysia and the Node.js adapter using pnpm for a JavaScript project. Note that pnpm may not install peer dependencies automatically.
```bash
pnpm add elysia @elysia/node @sinclair/typebox openapi-types
```
--------------------------------
### Create Hello World Server
Source: https://github.com/elysiajs/documentation/blob/main/docs/integrations/cheat-sheet.md
A basic Elysia server that responds with 'Hello World' to root requests. Starts a server on port 3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', () => 'Hello World')
.listen(3000)
```
--------------------------------
### Initialize Elysia Project with Prisma
Source: https://github.com/elysiajs/documentation/blob/main/docs/blog/with-prisma.md
Command to create a new Elysia project with Prisma integration. This sets up the basic project structure and installs necessary dependencies.
```bash
bun create elysia elysia-prisma
```
--------------------------------
### Set Execute Permissions and Run Binary
Source: https://github.com/elysiajs/documentation/blob/main/docs/patterns/deploy.md
On Linux, you may need to explicitly set execute permissions on the compiled binary before running it. This command grants execute permissions and then starts the server.
```bash
chmod +x ./server
./server
```
--------------------------------
### Enable Resource Detectors via Environment Variable
Source: https://github.com/elysiajs/documentation/blob/main/docs/plugins/opentelemetry.md
Configure resource detectors using the OTEL_NODE_RESOURCE_DETECTORS environment variable. This example enables only the 'env' and 'host' detectors.
```bash
export OTEL_NODE_RESOURCE_DETECTORS="env,host"
```