### ElysiaJS Hello World Example
Source: https://elysiajs.com/at-glance
A basic 'Hello World' example demonstrating how to set up a simple ElysiaJS server with GET, POST, and dynamic route handlers. This is a good starting point for new ElysiaJS projects.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'Hello Elysia')
.get('/user/:id', ({ params: { id } }) => id)
.post('/form', ({ body }) => body)
.listen(3000)
```
--------------------------------
### Basic WebSocket Server Setup
Source: https://elysiajs.com/patterns/websocket
Sets up a basic WebSocket server that echoes received messages back to the client. This is a fundamental example for initiating WebSocket communication.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.ws('/ws', {
message(ws, message) {
ws.send(message)
}
})
.listen(3000)
```
--------------------------------
### Cloning TypeGen Example Repository
Source: https://elysiajs.com/tutorial/features/openapi
To try the OpenAPI TypeGen feature locally, clone the example repository, install dependencies, and run the development server.
```bash
git clone https://github.com/SaltyAom/elysia-typegen-example && \
cd elysia-typegen-example && \
bun install && \
bun run dev
```
--------------------------------
### Define a Basic GET Route
Source: https://elysiajs.com/tutorial/getting-started/your-first-route
This snippet shows how to create a simple GET route that responds with 'Hello World!' on the root path. It requires importing Elysia and starting the server on port 3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'Hello World!')
.listen(3000)
```
--------------------------------
### Install OpenAPI Plugin
Source: https://elysiajs.com/plugins/openapi
Install the OpenAPI plugin using bun.
```bash
bun add @elysia/openapi
```
--------------------------------
### Install Static Plugin
Source: https://elysiajs.com/plugins/static
Install the @elysiajs/static plugin using bun.
```bash
bun add @elysiajs/static
```
--------------------------------
### Install Server Timing Plugin
Source: https://elysiajs.com/plugins/server-timing
Install the Server Timing plugin using Bun.
```bash
bun add @elysia/server-timing
```
--------------------------------
### Install Swagger Plugin
Source: https://elysiajs.com/plugins/swagger
Install the Swagger plugin using Bun.
```bash
bun add @elysia/swagger
```
--------------------------------
### Install Cron Plugin
Source: https://elysiajs.com/plugins/cron
Install the @elysia/cron package using Bun.
```bash
bun add @elysia/cron
```
--------------------------------
### Install Prisma and Prismabox
Source: https://elysiajs.com/integrations/prisma
Install the necessary packages for Prisma, Prismabox, and the Prisma adapter for Bun SQLite.
```bash
bun add @prisma/client prismabox prisma-adapter-bun-sqlite && \
bun add -d prisma
```
--------------------------------
### Install Bearer Plugin
Source: https://elysiajs.com/plugins/bearer
Install the Bearer plugin using bun.
```bash
bun add @elysiajs/bearer
```
--------------------------------
### Basic OpenTelemetry Setup
Source: https://elysiajs.com/patterns/opentelemetry
Install the `@elysia/opentelemetry` plugin 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())
```
--------------------------------
### Start Development Server
Source: https://elysiajs.com/integrations/cloudflare-worker
Run the Wrangler development server.
```bash
wrangler dev
```
--------------------------------
### Install GraphQL Yoga Plugin
Source: https://elysiajs.com/plugins/graphql-yoga
Install the GraphQL Yoga plugin for Elysia using Bun.
```bash
bun add @elysia/graphql-yoga
```
--------------------------------
### Install Production Dependencies
Source: https://elysiajs.com/patterns/opentelemetry
On the production server, use `bun install --production` to install only the necessary dependencies listed in `package.json`. This ensures that the application runs with the correct modules and avoids including development-specific packages.
```bash
bun install --production
```
--------------------------------
### Install Bun on Windows
Source: https://elysiajs.com/quick-start
Installs Bun using a PowerShell command. Recommended for Windows users.
```powershell
powershell -c "irm bun.sh/install.ps1 | iex"
```
--------------------------------
### Install Netlify CLI
Source: https://elysiajs.com/integrations/netlify
Install the Netlify CLI globally using Bun to test Elysia Edge Functions locally.
```bash
bun add -g netlify-cli
```
--------------------------------
### Install and Use Elysia HTML Plugin
Source: https://elysiajs.com/plugins/html
Install the plugin using bun and integrate it into your Elysia application to serve HTML content. This example demonstrates serving a basic HTML string and a JSX component.
```bash
bun add @elysiajs/html
```
```tsx
import React from 'react'
// ---cut---
import { Elysia } from 'elysia'
import { html, Html } from '@elysia/html'
new Elysia()
.use(html())
.get(
'/html',
() => `
Hello World
Hello World
`
)
.get('/jsx', () => (
Hello World
Hello World
))
.listen(3000)
```
--------------------------------
### Define Elysia Server in TanStack Start Route
Source: https://elysiajs.com/integrations/tanstack-start
Set up an Elysia server within a TanStack Start route file to handle API requests. This example shows basic GET and POST handlers.
```typescript
import { Elysia } from 'elysia'
import { createFileRoute } from '@tanstack/react-router'
import { createIsomorphicFn } from '@tanstack/react-start'
const app = new Elysia({
prefix: '/api' // [!code ++]
}).get('/', 'Hello Elysia!')
const handle = ({ request }: { request: Request }) => app.fetch(request) // [!code ++]
export const Route = createFileRoute('/api/$')({
server: {
handlers: {
GET: handle, // [!code ++]
POST: handle // [!code ++]
}
}
})
```
--------------------------------
### Basic Handler: Returning a String
Source: https://elysiajs.com/essential/handler
A simple handler that returns a string 'hello world' for a GET request to the root path. Requires Elysia to be imported and a server to be started on port 3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
// the function `() => 'hello world'` is a handler
.get('/', () => 'hello world')
.listen(3000)
```
--------------------------------
### Basic OpenTelemetry Setup
Source: https://elysiajs.com/plugins/opentelemetry
Install and apply the @elysia/opentelemetry plugin to your Elysia instance. This basic setup configures span processors using BatchSpanProcessor and OTLPTraceExporter.
```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 CORS Plugin
Source: https://elysiajs.com/plugins/cors
Install the CORS plugin using Bun.
```bash
bun add @elysia/cors
```
--------------------------------
### Install GraphQL Apollo Plugin
Source: https://elysiajs.com/plugins/graphql-apollo
Install the necessary packages for the GraphQL Apollo plugin using Bun.
```bash
bun add graphql @elysia/apollo @apollo/server
```
--------------------------------
### Run Compiled Elysia Binary
Source: https://elysiajs.com/patterns/deploy
Execute the compiled Elysia application binary to start the server. This binary is portable and does not require Bun to be installed on the target machine.
```bash
./server
```
--------------------------------
### Install Node.js on Windows
Source: https://elysiajs.com/quick-start
Installs Node.js using Chocolatey. Recommended for Windows users.
```powershell
choco install nodejs
```
--------------------------------
### Install Elysia with bun (Web Standard)
Source: https://elysiajs.com/quick-start
Installs Elysia for use with runtimes that support Web Standard Request/Response.
```bash
bun install elysia
```
--------------------------------
### Install Production Dependencies
Source: https://elysiajs.com/patterns/deploy
Run this command on your production server after building your application to install only the necessary production dependencies, excluding development tools.
```bash
bun install --production
```
--------------------------------
### Fetch Request with Query Parameters
Source: https://elysiajs.com/essential/validation
Example of sending a GET request with query parameters using the Fetch API.
```typescript
fetch('https://elysiajs.com/?name=Elysia')
```
--------------------------------
### Install Eden and Elysia
Source: https://elysiajs.com/eden/installation
Install the necessary packages for Eden and Elysia on your frontend project.
```bash
bun add @elysia/eden
bun add -d elysia
```
--------------------------------
### Install Elysia with npm
Source: https://elysiajs.com/quick-start
Installs Elysia, Node.js adapter, and development tools like tsx.
```bash
npm install elysia @elysia/node && \
npm install --save-dev tsx @types/node typescript
```
--------------------------------
### Install Node.js Adapter for Elysia
Source: https://elysiajs.com/integrations/node
Install the Elysia Node 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 Bun on MacOS/Linux
Source: https://elysiajs.com/quick-start
Installs Bun using a curl command. Recommended for MacOS and Linux users.
```bash
curl -fsSL https://bun.sh/install | bash
```
--------------------------------
### Install Bun Type Definitions
Source: https://elysiajs.com/eden/installation
Install Bun type definitions if you are using Bun-specific features in your handlers and returning them.
```bash
bun add -d @types/bun
```
--------------------------------
### Combined Status, Headers, and Redirect Example
Source: https://elysiajs.com/tutorial/getting-started/status-and-headers
An example combining setting custom headers, a status code, and a redirect within different routes.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ status, set }) => {
set.headers['x-powered-by'] = 'Elysia'
return status(418, 'Hello Elysia!')
})
.get('/docs', ({ redirect }) => redirect('https://elysiajs.com'))
.listen(3000)
```
--------------------------------
### Install Elysia with yarn
Source: https://elysiajs.com/quick-start
Installs Elysia, Node.js adapter, and development tools like tsx.
```bash
yarn add elysia @elysia/node && \
yarn add -D tsx @types/node typescript
```
--------------------------------
### Start Elysia Development Server
Source: https://elysiajs.com/quick-start
Launches the Elysia development server, enabling hot-reloading.
```bash
bun dev
```
--------------------------------
### Install Node.js on MacOS
Source: https://elysiajs.com/quick-start
Installs Node.js using Homebrew. Recommended for MacOS users.
```bash
brew install node
```
--------------------------------
### Install Elysia with bun (JavaScript)
Source: https://elysiajs.com/quick-start
Installs Elysia and the Node.js adapter for a JavaScript-based Elysia application.
```bash
bun add elysia @elysia/node
```
--------------------------------
### Install Elysia with pnpm (Web Standard)
Source: https://elysiajs.com/quick-start
Installs Elysia, TypeBox, and OpenAPI types for use with Web Standard runtimes.
```bash
pnpm install elysia @sinclair/typebox openapi-types
```
--------------------------------
### Install Peer Dependencies for pnpm
Source: https://elysiajs.com/integrations/astro
If using pnpm, manually install @sinclair/typebox and openapi-types as they are not automatically installed by default.
```bash
pnpm add @sinclair/typebox openapi-types
```
--------------------------------
### Install Optional Peer Dependencies
Source: https://elysiajs.com/plugins/graphql-yoga
Install optional peer dependencies for GraphQL Yoga if needed.
```bash
bun add graphql graphql-yoga
```
--------------------------------
### Install Elysia with yarn (Web Standard)
Source: https://elysiajs.com/quick-start
Installs Elysia for use with runtimes that support Web Standard Request/Response.
```bash
yarn add elysia
```
--------------------------------
### Install Elysia with npm (JavaScript)
Source: https://elysiajs.com/quick-start
Installs Elysia and the Node.js adapter for a JavaScript-based Elysia application.
```bash
npm install elysia @elysia/node
```
--------------------------------
### Install Elysia with npm (Web Standard)
Source: https://elysiajs.com/quick-start
Installs Elysia for use with runtimes that support Web Standard Request/Response.
```bash
npm install elysia
```
--------------------------------
### Install Elysia with yarn (JavaScript)
Source: https://elysiajs.com/quick-start
Installs Elysia and the Node.js adapter for a JavaScript-based Elysia application.
```bash
yarn add elysia @elysia/node
```
--------------------------------
### Install Drizzle and Drizzle Typebox
Source: https://elysiajs.com/integrations/drizzle
Install the necessary packages for Drizzle ORM and its integration with Elysia via drizzle-typebox.
```bash
bun add drizzle-orm drizzle-typebox
```
--------------------------------
### Install Development Dependencies (tsx, @types/node, typescript)
Source: https://elysiajs.com/integrations/node
Install development tools for TypeScript support and hot-reloading.
```bash
bun add -d tsx @types/node typescript
```
```bash
pnpm add -D tsx @types/node typescript
```
```bash
npm install --save-dev tsx @types/node typescript
```
```bash
yarn add -D tsx @types/node typescript
```
--------------------------------
### Install React Email and Dependencies
Source: https://elysiajs.com/integrations/react-email
Install React Email and its necessary components using Bun. This command adds React Email as a development dependency and React and ReactDOM as regular dependencies.
```bash
bun add -d react-email
bun add @react-email/components react react-dom
```
--------------------------------
### Install Node.js on Arch Linux
Source: https://elysiajs.com/quick-start
Installs Node.js and npm using the pacman package manager. Recommended for Arch Linux users.
```bash
pacman -S nodejs npm
```
--------------------------------
### Configure package.json Scripts for Development and Production
Source: https://elysiajs.com/integrations/node
Add scripts to package.json for development, building, and starting the production server.
```json
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc src/index.ts --outDir dist",
"start": "NODE_ENV=production node dist/index.js"
}
}
```
--------------------------------
### Install nuxt-elysia Plugin
Source: https://elysiajs.com/integrations/nuxt
Install the nuxt-elysia plugin and Elysia with Eden Treaty using bun. For pnpm users, additional peer dependencies might be required.
```bash
bun add elysia @elysia/eden
bun add -d nuxt-elysia
```
--------------------------------
### Install Elysia with pnpm
Source: https://elysiajs.com/quick-start
Installs Elysia, Node.js adapter, TypeBox, OpenAPI types, and development tools like tsx.
```bash
pnpm add elysia @elysia/node @sinclair/typebox openapi-types && \
pnpm add -D tsx @types/node typescript
```
--------------------------------
### Install Node.js on Linux (apt)
Source: https://elysiajs.com/quick-start
Installs Node.js using the apt package manager. Recommended for Debian/Ubuntu-based Linux distributions.
```bash
sudo apt install nodejs
```
--------------------------------
### Basic GraphQL Apollo Setup
Source: https://elysiajs.com/plugins/graphql-apollo
Integrate the Apollo plugin into an Elysia application with type definitions and resolvers.
```typescript
import { Elysia } from 'elysia'
import { apollo, gql } from '@elysia/apollo'
const app = new Elysia()
.use(
apollo({
typeDefs: gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`,
resolvers: {
Query: {
books: () => {
return [
{
title: 'Elysia',
author: 'saltyAom'
}
]
}
}
}
})
)
.listen(3000)
```
--------------------------------
### Basic Handler: Returning a String
Source: https://elysiajs.com/tutorial/getting-started/handler-and-context
Defines a simple GET route that returns a static string 'hello world' as the response.
```typescript
import { Elysia } from 'elysia'
new Elysia()
// `() => 'hello world'` is a handler
.get('/', () => 'hello world')
.listen(3000)
```
--------------------------------
### Elysia Server Setup with Eden Treaty
Source: https://elysiajs.com/eden/overview
Defines an Elysia server with multiple routes, including a GET, a PUT with a typed body, and another GET. This setup is designed to be used with Eden Treaty for type-safe client interactions.
```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
```
--------------------------------
### Install Elysia with pnpm (JavaScript)
Source: https://elysiajs.com/quick-start
Installs Elysia and the Node.js adapter, including TypeBox and OpenAPI types, for a JavaScript Elysia application.
```bash
pnpm add elysia @elysia/node @sinclair/typebox openapi-types
```
--------------------------------
### Serve Elysia Application with Deno
Source: https://elysiajs.com/integrations/deno
Command to start the Elysia server using Deno. The --watch flag enables hot-reloading.
```bash
deno serve --watch src/index.ts
```
--------------------------------
### Frontend/Backend Module Resolution Example
Source: https://elysiajs.com/eden/installation
A confirmation import statement demonstrating that the path alias correctly resolves the same module in both frontend and backend environments.
```typescript
// This should be able to resolve the same module in both frontend and backend, and not `any`
import { a, b } from '@/controllers'
```
--------------------------------
### Define Basic Routes with GET Method
Source: https://elysiajs.com/essential/route
Define multiple routes using the GET HTTP verb and string literals for responses. Access the server at http://localhost:3000.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'hello')
.get('/hi', 'hi')
.listen(3000)
```
--------------------------------
### Header Prioritization Example
Source: https://elysiajs.com/eden/treaty/config
Demonstrates how inline headers override config headers, which in turn override fetch headers.
```typescript
const api = treaty('localhost:3000', {
headers: {
authorization: 'Bearer Aponia'
}
})
api.profile.get({
headers: {
authorization: 'Bearer Griseo'
}
})
```
```typescript
fetch('http://localhost:3000', {
headers: {
authorization: 'Bearer Griseo'
}
})
```
--------------------------------
### Basic HTTP Methods in Elysia
Source: https://elysiajs.com/essential/route
Demonstrates the basic usage of GET and POST methods in Elysia.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'hello')
.post('/hi', 'hi')
.listen(3000)
```
--------------------------------
### GET Request with Fetch Parameters
Source: https://elysiajs.com/eden/treaty/parameters
Demonstrates how to pass native Fetch API parameters, such as signal for aborting requests.
```APIDOC
## GET /hello (with Fetch parameters)
### Description
Retrieves a greeting from the server, with the ability to control the fetch behavior.
### Method
GET
### Endpoint
/hello
### Parameters
#### Fetch Parameters
- **signal** (AbortSignal) - Optional - Allows aborting the fetch request.
### Request Example
(No request body for GET requests)
### Response
#### Success Response (200)
- (No specific fields documented, returns 'hi')
```
--------------------------------
### Elysia Limitation Example
Source: https://elysiajs.com/integrations/cloudflare-worker
This code demonstrates a limitation where defining a Response before server start will throw an error.
```typescript
import { Elysia } from 'elysia'
new Elysia()
// This will throw error
.get('/', 'Hello Elysia')
.listen(3000)
```
--------------------------------
### Example of Route Prefixing
Source: https://elysiajs.com/patterns/configuration
Illustrates how a defined prefix is applied to a route, changing its accessible path.
```typescript
import { Elysia, t } from 'elysia'
new Elysia({ prefix: '/v1' }).get('/name', 'elysia') // Path is /v1/name
```
--------------------------------
### WebSocket Server and Client Setup
Source: https://elysiajs.com/eden/treaty/websocket
Sets up a WebSocket server with message echoing and demonstrates client-side subscription and message sending using Eden Treaty.
```typescript
import { Elysia, t } from "elysia";
import { treaty } from "@elysia/eden";
const app = new Elysia()
.ws("/chat", {
body: t.String(),
response: t.String(),
message(ws, message) {
ws.send(message);
},
})
.listen(3000);
const api = treaty("localhost:3000");
const chat = api.chat.subscribe();
chat.subscribe((message) => {
console.log("got", message);
});
chat.on("open", () => {
chat.send("hello from client");
});
```
--------------------------------
### Basic Better Auth Setup
Source: https://elysiajs.com/integrations/better-auth
Initializes a Better Auth instance with a PostgreSQL connection pool. This is the foundational step for using Better Auth.
```typescript
import { betterAuth } from 'better-auth'
import { Pool } from 'pg'
export const auth = betterAuth({
database: new Pool()
})
```
--------------------------------
### Deferred Module Registration
Source: https://elysiajs.com/essential/plugin
Illustrates how to define an asynchronous plugin that can be registered after the server has started, preventing it from blocking server startup.
```typescript
// plugin.ts
import { Elysia, file } from 'elysia'
import { loadAllFiles } from './files'
export const loadStatic = async (app: Elysia) => {
const files = await loadAllFiles()
files.forEach((asset) => app
.get(asset, file(file))
)
return app
}
```
--------------------------------
### Remap Plugin Properties with Prefix and Suffix
Source: https://elysiajs.com/patterns/extends-context
Use the `prefix` function to remap properties of a plugin, preventing name collisions and simplifying access. This example demonstrates remapping properties from the 'setup' plugin.
```typescript
import { Elysia } from 'elysia'
const setup = new Elysia({ name: 'setup' })
.decorate({
argon: 'a',
boron: 'b',
carbon: 'c'
})
const app = new Elysia()
.use(setup)
.prefix('decorator', 'setup')
.get('/', ({ setupCarbon, ...rest }) => setupCarbon)
```
--------------------------------
### Define a Wildcard Route
Source: https://elysiajs.com/tutorial/getting-started/your-first-route
This snippet demonstrates defining a wildcard GET route '/id/*' which captures all subsequent path segments. The captured value is available in params['*']. Elysia needs to be imported and the server started.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/id/*', ({ params }) => params['*'])
.listen(3000)
```
--------------------------------
### Integrate Eden Treaty for Type Safety
Source: https://elysiajs.com/integrations/tanstack-start
Add Eden Treaty to your Elysia and TanStack Start setup for end-to-end type safety. This snippet demonstrates creating isomorphic functions for both server and client treaty instances.
```typescript
import { Elysia } from 'elysia'
import { treaty } from '@elysia/eden' // [!code ++]
import { createFileRoute } from '@tanstack/react-router'
import { createIsomorphicFn } from '@tanstack/react-start'
const app = new Elysia({
prefix: '/api'
}).get('/', 'Hello Elysia!')
const handle = ({ request }: { request: Request }) => app.fetch(request)
export const Route = createFileRoute('/api/$')({
server: {
handlers: {
GET: handle,
POST: handle
}
}
})
export const getTreaty = createIsomorphicFn() // [!code ++]
.server(() => treaty(app).api) // [!code ++]
.client(() => treaty('localhost:3000').api) // [!code ++]
```
--------------------------------
### Define an Optional Dynamic Route Parameter
Source: https://elysiajs.com/tutorial/getting-started/your-first-route
This example shows how to define a dynamic route '/id/:id?' where the 'id' parameter is optional. The handler will receive the 'id' if provided, otherwise it will be undefined. Elysia must be imported and the server started.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/id/:id?', ({ params: { id } }) => `id ${id}`)
.listen(3000)
```
--------------------------------
### Define a Dynamic Route with Parameter Capture
Source: https://elysiajs.com/tutorial/getting-started/your-first-route
This snippet illustrates creating a dynamic GET route '/id/:id' that captures the 'id' segment from the URL. The captured value is then returned by the handler. Requires Elysia import and server start.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.get('/id/:id', ({ params: { id } }) => id)
.listen(3000)
```
--------------------------------
### GET Request with Additional Parameters
Source: https://elysiajs.com/eden/treaty/parameters
Shows how to send query and headers for a GET request, as GET requests do not typically have a request body.
```APIDOC
## GET /hello
### Description
Retrieves a greeting from the server.
### Method
GET
### Endpoint
/hello
### Parameters
#### Query Parameters
(None explicitly documented for this example)
#### Headers
- **hello** (string) - Optional - A custom header.
### Request Example
(No request body for GET requests)
### Response
#### Success Response (200)
- (No specific fields documented, returns 'hi')
```
--------------------------------
### Set Up GraphQL Server with Yoga
Source: https://elysiajs.com/integrations/cheat-sheet
Integrate a GraphQL server using the @elysiajs/graphql-yoga plugin. This example defines GraphQL schema and resolvers for a simple query.
```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)
```
--------------------------------
### Build Elysia Fullstack Server for Production
Source: https://elysiajs.com/patterns/fullstack-dev-server
Compile the Elysia fullstack server into a single executable file using `bun build`. Ensure the `public` folder is included when running the executable.
```bash
bun build --compile --target bun --outfile server src/index.ts
```
--------------------------------
### Creating a Reusable Plugin with Configuration
Source: https://elysiajs.com/essential/plugin
Demonstrates how to create a reusable plugin that accepts configuration parameters to customize its behavior, such as setting a version number.
```typescript
import { Elysia } from 'elysia'
const version = (version = 1) => new Elysia()
.get('/version', version)
const app = new Elysia()
.use(version(1))
.listen(3000)
```
--------------------------------
### Create New Elysia App with Bun
Source: https://elysiajs.com/quick-start
Scaffolds a new Elysia project directory named 'app'.
```bash
bun create elysia app
```
--------------------------------
### Bun Configuration for Preloading
Source: https://elysiajs.com/patterns/opentelemetry
Configure Bun to preload the OpenTelemetry setup file before running the main application. This ensures that the SDK is initialized and ready before any instrumented modules are imported.
```toml
preload = ["./src/instrumentation.ts"]
```
--------------------------------
### OpenTelemetry Setup with PgInstrumentation
Source: https://elysiajs.com/patterns/opentelemetry
This snippet demonstrates how to initialize OpenTelemetry with a specific instrumentation, like PgInstrumentation, in a separate file. Ensure the OpenTelemetry SDK runs before importing the target module.
```typescript
import { opentelemetry } from '@elysia/opentelemetry'
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'
export const instrumentation = opentelemetry({
instrumentations: [new PgInstrumentation()]
})
```
--------------------------------
### Creating and Using a Simple Plugin
Source: https://elysiajs.com/essential/plugin
Demonstrates how to create a standalone plugin instance and use it within another Elysia instance. The plugin adds a 'plugin' decoration and a '/plugin' route.
```typescript
import { Elysia } from 'elysia'
const plugin = new Elysia()
.decorate('plugin', 'hi')
.get('/plugin', ({ plugin }) => plugin)
const app = new Elysia()
.use(plugin)
.get('/', ({ plugin }) => plugin)
// ^?
.listen(3000)
```
--------------------------------
### Enable HTTPS/TLS with Certificate and Key
Source: https://elysiajs.com/patterns/configuration
Configure the server to use HTTPS by providing 'cert' and 'key' files within the 'serve.tls' option. Both are required to enable TLS.
```typescript
import { Elysia, file } from 'elysia'
new Elysia({
serve: {
ls: {
cert: file('cert.pem'),
key: file('key.pem')
}
}
})
```
--------------------------------
### Minimal Custom Error Message Example
Source: https://elysiajs.com/tutorial/patterns/validation-error
A basic example demonstrating how to assign a simple string as a custom error message to a number field.
```typescript
import { Elysia, t } from 'elysia'
new Elysia()
.post(
'/',
({ body }) => body,
{
body: t.Object({
age: t.Number({
error: 'thing' // [!code ++]
})
})
}
)
.listen(3000)
```
--------------------------------
### Install Tailwind CSS Dependencies
Source: https://elysiajs.com/patterns/fullstack-dev-server
Install Tailwind CSS and the Bun plugin for Tailwind. This is required for integrating Tailwind CSS with the Bun Fullstack Dev Server.
```bash
bun add tailwindcss@4
bun add -d bun-plugin-tailwind
```
--------------------------------
### Mount Elysia App into Hono, then into Elysia
Source: https://elysiajs.com/patterns/mount
Demonstrates nesting frameworks by mounting an Elysia app within a Hono app, and then mounting that Hono app into another Elysia app. This showcases deep interoperability.
```typescript
import { Elysia } from 'elysia'
import { Hono } from 'hono'
const elysia = new Elysia()
.get('/', () => 'Hello from Elysia inside Hono inside Elysia')
const hono = new Hono()
.get('/', (c) => c.text('Hello from Hono!'))
.mount('/elysia', elysia.fetch)
const main = new Elysia()
.get('/', () => 'Hello from Elysia')
.mount('/hono', hono.fetch)
.listen(3000)
```
--------------------------------
### Sending Only Additional Parameters for GET/HEAD
Source: https://elysiajs.com/eden/treaty/parameters
Illustrates sending only additional parameters (headers) to a GET endpoint, as GET requests do not typically have a request body. Headers are optional and defined by the server's schema.
```typescript
import { Elysia } from 'elysia'
import { treaty } from '@elysia/eden'
const app = new Elysia()
.get('/hello', () => 'hi')
.listen(3000)
const api = treaty('localhost:3000')
// ✅ works
api.hello.get({
// This is optional as not specified in schema
headers: {
hello: 'world'
}
})
```
--------------------------------
### Elysia with Native Static Response Example
Source: https://elysiajs.com/patterns/configuration
Demonstrates how enabling `nativeStaticResponse` can lead to optimized static value handling, similar to direct Bun.serve usage.
```typescript
import { Elysia } from 'elysia'
// This
new Elysia({
nativeStaticResponse: true
}).get('/version', 1)
// is an equivalent to
Bun.serve({
static: {
'/version': new Response(1)
}
})
```
--------------------------------
### Basic Authentication Hook Example
Source: https://elysiajs.com/tutorial/getting-started/guard
This example demonstrates a simple 'beforeHandle' hook to check for a 'name' query parameter. If 'name' is missing, it returns a 401 status code. This is a fundamental pattern for request validation.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.onBeforeHandle(({ query: { name }, status }) => {
if(!name) return status(401)
})
.get('/auth', ({ query: { name = 'anon' } }) => {
return `Hello ${name}!`
})
.get('/profile', ({ query: { name = 'anon' } }) => {
return `Hello ${name}!`
})
.listen(3000)
```
--------------------------------
### Basic Cron Job Setup
Source: https://elysiajs.com/plugins/cron
Set up a basic cron job that runs every 10 seconds and logs a message. The job is registered with the name 'heartbeat'.
```typescript
import { Elysia } from 'elysia'
import { cron } from '@elysia/cron'
new Elysia()
.use(
cron({
name: 'heartbeat',
pattern: '*/10 * * * * *',
run() {
console.log('Heartbeat')
}
})
)
.listen(3000)
```
--------------------------------
### Query and Parameter Validation
Source: https://elysiajs.com/essential/validation
Validates both query and parameter types for a GET request.
```typescript
import { Elysia, t } from 'elysia'
new Elysia()
.get('/id/:id', () => 'Hello World!', {
query: t.Object({
name: t.String()
}),
params: t.Object({
id: t.Number()
})
})
.listen(3000)
```
--------------------------------
### Create WebSocket Connection
Source: https://elysiajs.com/integrations/cheat-sheet
Set up a real-time connection using WebSocket. This snippet shows how to handle incoming messages and send responses.
```typescript
import { Elysia } from 'elysia'
new Elysia()
.ws('/ping', {
message(ws, message) {
ws.send('hello ' + message)
}
})
.listen(3000)
```
--------------------------------
### Basic Parameter Validation
Source: https://elysiajs.com/essential/validation
Validates that the 'id' parameter is a number for a GET request.
```typescript
import { Elysia, t } from 'elysia'
new Elysia()
.get('/id/:id', ({ params: { id } }) => id, {
params: t.Object({
id: t.Number()
})
})
.listen(3000)
```
--------------------------------
### Applying Route Prefixes with Plugin Instance
Source: https://elysiajs.com/essential/route
Illustrates how to use a prefix in the Elysia constructor to create a plugin instance with a base path, reducing nesting.
```typescript
import { Elysia } from 'elysia'
const users = new Elysia({ prefix: '/user' })
.post('/sign-in', 'Sign in')
.post('/sign-up', 'Sign up')
.post('/profile', 'Profile')
new Elysia()
.use(users)
.get('/', 'hello world')
.listen(3000)
```
--------------------------------
### Package.json Scripts (JavaScript)
Source: https://elysiajs.com/quick-start
Defines scripts for developing and starting a JavaScript Elysia application.
```json
{
"type": "module",
"scripts": {
"dev": "node src/index.js",
"start": "NODE_ENV=production node src/index.js"
}
}
```