### Basic ElysiaJS Server Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/SKILL.md Sets up a basic ElysiaJS server with a GET route for 'Hello World', a POST route for user creation with body validation, and a GET route for user ID with parameter validation and conditional response. ```typescript import { Elysia, t, status } from 'elysia' const app = new Elysia() .get('/', () => 'Hello World') .post('/user', ({ body }) => body, { body: t.Object({ name: t.String(), age: t.Number() }) }) .get('/id/:id', ({ params: { id } }) => { if(id > 1_000_000) return status(404, 'Not Found') return id }, { params: t.Object({ id: t.Number({ minimum: 1 }) }), response: { 200: t.Number(), 404: t.Literal('Not Found') } }) .listen(3000) ``` -------------------------------- ### Initialize a Basic ElysiaJS Server Source: https://context7.com/elysiajs/skills/llms.txt Demonstrates creating an application instance, defining GET and POST routes with parameter validation, and starting the server on a specified port. ```typescript import { Elysia, t, status } from 'elysia' const app = new Elysia() .get('/', () => 'Hello World') .post('/user', ({ body }) => body, { body: t.Object({ name: t.String(), age: t.Number() }) }) .get('/id/:id', ({ params: { id } }) => { if (id > 1_000_000) return status(404, 'Not Found') return id }, { params: t.Object({ id: t.Number({ minimum: 1 }) }), response: { 200: t.Number(), 404: t.Literal('Not Found') } }) .listen(3000) console.log(`Server running at http://localhost:3000`) ``` -------------------------------- ### Installation Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Install the OpenTelemetry plugin using Bun. ```APIDOC ## Installation ```bash bun add @elysiajs/opentelemetry ``` ``` -------------------------------- ### Install HTML Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/html.md Install the required package using Bun. ```bash bun add @elysiajs/html ``` -------------------------------- ### Installation Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/openapi.md Install the @elysiajs/openapi plugin using Bun. ```APIDOC ## Installation ```bash bun add @elysiajs/openapi ``` ``` -------------------------------- ### Install OpenTelemetry Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Install the OpenTelemetry plugin using Bun. ```bash bun add @elysiajs/opentelemetry ``` -------------------------------- ### Install Server Timing Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/server-timing.md Install the Server Timing plugin using bun. ```bash bun add @elysiajs/server-timing ``` -------------------------------- ### Install Elysia OpenAPI Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/openapi.md Install the OpenAPI plugin using bun. ```bash bun add @elysiajs/openapi ``` -------------------------------- ### Install GraphQL Yoga Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/graphql-yoga.md Install the plugin using the Bun package manager. ```bash bun add @elysiajs/graphql-yoga ``` -------------------------------- ### Exporting to Backends (Axiom Example) Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Example configuration for exporting traces to Axiom. ```APIDOC ## Export to Backends Example - Axiom: ```typescript .use(opentelemetry({ spanProcessors: [ new BatchSpanProcessor( new OTLPTraceExporter({ url: 'https://api.axiom.co/v1/traces', headers: { Authorization: `Bearer ${Bun.env.AXIOM_TOKEN}`, 'X-Axiom-Dataset': Bun.env.AXIOM_DATASET } }) ) ] })) ``` ``` -------------------------------- ### JWT Plugin Installation Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/jwt.md Install the JWT plugin using Bun. ```APIDOC ## Installation ```bash bun add @elysiajs/jwt ``` ``` -------------------------------- ### Install Elysia Static Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/static.md Install the plugin using the Bun package manager. ```bash bun add @elysiajs/static ``` -------------------------------- ### Install JWT Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/jwt.md Install the JWT plugin using Bun package manager. ```bash bun add @elysiajs/jwt ``` -------------------------------- ### Basic Usage Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/graphql-apollo.md Demonstrates the fundamental setup of the Apollo plugin with type definitions and resolvers. ```typescript import { Elysia } from 'elysia' import { apollo, gql } from '@elysiajs/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) ``` -------------------------------- ### Install XSS Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/html.md Install the KitaJS plugin for additional type-safe XSS reminders. ```sh bun add @kitajs/ts-html-plugin ``` -------------------------------- ### Install Prisma and prismabox dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/prisma.md Use bun to add the necessary Prisma client and prismabox generator packages. ```bash bun add @prisma/client prismabox && \ bun add -d prisma ``` -------------------------------- ### Basic GraphQL Server Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/graphql-yoga.md Initialize a basic Elysia server with GraphQL Yoga, defining schema 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) ``` -------------------------------- ### Install Eden Treaty and Elysia Source: https://github.com/elysiajs/skills/blob/main/elysia/references/eden.md Install the necessary packages for Eden Treaty and Elysia using Bun. ```bash bun add @elysiajs/eden bun add -d elysia ``` -------------------------------- ### Install Eden Testing Dependency Source: https://github.com/elysiajs/skills/blob/main/elysia/references/testing.md Install the @elysiajs/eden package as a development dependency. ```bash bun add -d @elysiajs/eden ``` -------------------------------- ### Advanced Instrumentation Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Instructions for setting up advanced instrumentation, including separating instrumentation logic and preloading. ```APIDOC ## Instrumentations (Advanced) SDK must run before importing instrumented module. ### Setup 1. Separate file: ```typescript // src/instrumentation.ts import { opentelemetry } from '@elysiajs/opentelemetry' import { PgInstrumentation } from '@opentelemetry/instrumentation-pg' export const instrumentation = opentelemetry({ instrumentations: [new PgInstrumentation()] }) ``` 2. Apply: ```typescript // src/index.ts import { instrumentation } from './instrumentation' new Elysia().use(instrumentation).listen(3000) ``` 3. Preload: ```toml # bunfig.toml preload = ["./src/instrumentation.ts"] ``` ``` -------------------------------- ### Install development dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nodejs.md Install tsx and TypeScript types for hot-reloading and development support. ```bash bun add -d tsx @types/node typescript ``` -------------------------------- ### Install Elysia Node.js dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nodejs.md Install the necessary packages to run Elysia on Node.js using bun. ```bash bun add elysia @elysiajs/node ``` -------------------------------- ### Install Apollo Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/graphql-apollo.md Install the necessary dependencies for Apollo GraphQL integration in Elysia. ```bash bun add graphql @elysiajs/apollo @apollo/server ``` -------------------------------- ### Define Elysia API Route Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nuxt.md Create an `api.ts` file to define your Elysia API routes. This example sets up a simple '/hello' GET endpoint. ```typescript // api.ts export default () => new Elysia() .get('/hello', () => ({ message: 'Hello world!' })) ``` -------------------------------- ### Define HTML and React Entry Points Source: https://github.com/elysiajs/skills/blob/main/elysia/references/bun-fullstack-dev-server.md Standard HTML structure and React root rendering setup for the frontend. ```html Elysia React App
``` ```tsx // public/index.tsx import { useState } from 'react' import { createRoot } from 'react-dom/client' function App() { const [count, setCount] = useState(0) const increase = () => setCount((c) => c + 1) return (

{count}

) } const root = createRoot(document.getElementById('root')!) root.render() ``` -------------------------------- ### Install Wrangler CLI Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/cloudflare-worker.md Initialize a new project for Cloudflare Workers using the Wrangler CLI. ```bash wrangler init elysia-on-cloudflare ``` -------------------------------- ### Install Drizzle Dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/drizzle.md Install the necessary Drizzle ORM and typebox packages. ```bash bun add drizzle-orm drizzle-typebox ``` -------------------------------- ### AutoDoctype Configuration Example Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/html.md Demonstrates the difference in doctype handling when using the plugin versus manual return. ```ts // without the plugin app.get('/', () => '') // With the plugin app.get('/', ({ html }) => html('')) ``` -------------------------------- ### Install Cron Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/cron.md Use the Bun package manager to add the cron plugin to your project. ```bash bun add @elysiajs/cron ``` -------------------------------- ### Install Nuxt Elysia Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nuxt.md Install the necessary packages for ElysiaJS and the Nuxt integration plugin. ```bash bun add elysia @elysiajs/eden bun add -d nuxt-elysia ``` ```bash pnpm add @sinclair/typebox openapi-types ``` -------------------------------- ### Start Email Preview Server Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/react-email.md Run the React Email development server using Bun. This command will open a browser window where you can preview your email templates. ```bash bun email ``` -------------------------------- ### Install Tailwind CSS Dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/references/bun-fullstack-dev-server.md Commands to add Tailwind CSS and the Bun plugin. ```bash bun add tailwindcss@4 bun add -d bun-plugin-tailwind ``` -------------------------------- ### Configure Path Aliases Source: https://github.com/elysiajs/skills/blob/main/elysia/references/bun-fullstack-dev-server.md Sets up path mapping in tsconfig.json and usage example. ```json { "compilerOptions": { "baseUrl": ".", "paths": { "@public/*": ["public/*"] } } } ``` ```tsx import '@public/global.css' ``` -------------------------------- ### Production Installation Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Install only production dependencies to keep the `node_modules` directory clean while ensuring instrumented libraries are available at runtime. ```bash bun install --production ``` -------------------------------- ### Install Elysia CORS Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/cors.md Install the CORS plugin for Elysia using bun. ```bash bun add @elysiajs/cors ``` -------------------------------- ### Eden Treaty Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/references/testing.md Initialize the Eden treaty client for type-safe API testing. ```typescript import { treaty } from '@elysiajs/eden' import { app } from '../src/modules/auth' const api = treaty(app) ``` -------------------------------- ### Install Optional Peer Dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/graphql-yoga.md Install specific versions of GraphQL and GraphQL Yoga as peer dependencies. ```bash bun add graphql graphql-yoga ``` -------------------------------- ### Install React Email Dependencies Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/react-email.md Install the necessary packages for React Email development. Use the `-d` flag for development dependencies. ```bash bun add -d react-email bun add @react-email/components react react-dom ``` -------------------------------- ### Setup Custom Instrumentation Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Configure custom instrumentations, such as for PostgreSQL, in a separate file and export it for use within Elysia. ```typescript // src/instrumentation.ts import { opentelemetry } from '@elysiajs/opentelemetry' import { PgInstrumentation } from '@opentelemetry/instrumentation-pg' export const instrumentation = opentelemetry({ instrumentations: [new PgInstrumentation()] }) ``` ```typescript // src/index.ts import { instrumentation } from './instrumentation' new Elysia().use(instrumentation).listen(3000) ``` -------------------------------- ### Install Bearer Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/bearer.md Use the Bun package manager to add the @elysiajs/bearer dependency to your project. ```bash bun add @elysiajs/bearer ``` -------------------------------- ### Auth Module Implementation Source: https://github.com/elysiajs/skills/blob/main/elysia/references/testing.md Example of an authentication module using cookies and validation. ```typescript // src/modules/auth/index.ts import { Elysia, t } from 'elysia' export const authModule = new Elysia({ prefix: '/auth' }) .post('/login', ({ body, cookie: { session } }) => { if (body.username === 'admin' && body.password === 'password') { session.value = 'valid-session' return { success: true } } return { success: false } }, { body: t.Object({ username: t.String(), password: t.String() }) }) .get('/profile', ({ cookie: { session }, status }) => { if (!session.value) { return status(401, { error: 'Unauthorized' }) } return { username: 'admin' } }) ``` -------------------------------- ### Eden Client Setup for Next.js Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nextjs.md Create an isomorphic Eden client for Elysia. Use `process.env` to conditionally initialize the client for server-side (direct call) or client-side (network call) environments. ```typescript // lib/eden.ts import { treaty } from '@elysiajs/eden' import type { app } from '../app/api/[[...slugs]]/route' export const api = typeof process !== 'undefined' ? treaty(app).api : treaty('localhost:3000').api ``` -------------------------------- ### Production Server Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Configures an Elysia application with AOT compilation, CORS, and OpenTelemetry, including a graceful shutdown handler. ```typescript // src/server.ts import { Elysia } from 'elysia' import { cors } from '@elysiajs/cors' import { opentelemetry } from '@elysiajs/opentelemetry' export const app = new Elysia({ aot: true, nativeStaticResponse: true }) .use(cors({ origin: process.env.CORS_ORIGIN || 'http://localhost:3000' })) .use(opentelemetry({ serviceName: 'my-service' })) .get('/health', () => ({ status: 'ok' })) .get('/', () => 'Hello Production') .listen(parseInt(process.env.PORT || '3000')) // Graceful shutdown process.on('SIGTERM', () => { app.stop() process.exit(0) }) ``` -------------------------------- ### ElysiaJS HTTP Methods Source: https://github.com/elysiajs/skills/blob/main/elysia/SKILL.md Demonstrates setting up basic HTTP routes for GET, POST, PUT, PATCH, DELETE, OPTIONS, and HEAD methods in ElysiaJS. ```typescript import { Elysia } from 'elysia' new Elysia() .get('/', 'GET') .post('/', 'POST') .put('/', 'PUT') .patch('/', 'PATCH') .delete('/', 'DELETE') .options('/', 'OPTIONS') .head('/', 'HEAD') ``` -------------------------------- ### Configure Plugin Instance Source: https://github.com/elysiajs/skills/blob/main/elysia/references/plugin.md Create a factory function to instantiate plugins with specific configurations. This allows for dynamic setup of plugin behavior. ```typescript // Instance factory with config const version = (v = 1) => new Elysia() .get('/version', v) const app = new Elysia() .use(version(1)) ``` -------------------------------- ### Environment Variables in .env File Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Example of an .env file for configuring application settings like NODE_ENV, PORT, DATABASE_URL, JWT_SECRET, and CORS_ORIGIN. ```env NODE_ENV=production PORT=3000 DATABASE_URL=postgresql://user:password@localhost:5432/db JWT_SECRET=your-secret-key CORS_ORIGIN=https://example.com ``` -------------------------------- ### OpenTelemetry Monitoring for Elysia Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Integrate OpenTelemetry for monitoring your Elysia application. This example shows basic setup with service name and endpoint configuration. ```typescript import { opentelemetry } from '@elysiajs/opentelemetry' new Elysia() .use(opentelemetry({ serviceName: 'my-service', endpoint: 'http://localhost:4318' })) ``` -------------------------------- ### GET/HEAD Request with Options Source: https://github.com/elysiajs/skills/blob/main/elysia/references/eden.md Make GET or HEAD requests, optionally including headers, query parameters, or fetch options. ```typescript .hello.get({ headers: {}, query: {}, fetch: {} }) ``` -------------------------------- ### Basic Elysia OpenTelemetry Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Initialize Elysia with the OpenTelemetry plugin, configuring span processors and trace exporters. Auto-collects spans from compatible libraries. ```typescript 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()) ] })) ``` -------------------------------- ### Export Elysia Server as Default Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/vercel.md Export your Elysia server instance as the default export in `src/index.ts` for Vercel deployment. This setup includes a GET and a POST route. ```typescript import { Elysia, t } from 'elysia' export default new Elysia() .get('/', () => 'Hello Vercel Function') .post('/', ({ body }) => body, { body: t.Object({ name: t.String() }) }) ``` -------------------------------- ### Elysia Application for Unit Testing Source: https://context7.com/elysiajs/skills/llms.txt An Elysia application setup designed for direct testing using the .handle() method. It includes routes for GET and POST requests with schema validation. ```typescript // app.ts import { Elysia, t } from 'elysia' export const app = new Elysia() .get('/', () => 'Hello World') .get('/user/:id', ({ params }) => ({ id: params.id, name: 'Test User' })) .post('/user', ({ body }) => body, { body: t.Object({ name: t.String(), age: t.Number({ minimum: 0 }) }) }) ``` -------------------------------- ### Lazy Load Modules with Dynamic Import Source: https://github.com/elysiajs/skills/blob/main/elysia/references/plugin.md Employ dynamic `import()` within `.use()` to load plugins after the server has started, improving initial startup performance. ```typescript const app = new Elysia() .use(import('./plugin')) // loaded after startup ``` -------------------------------- ### Configure package.json for Email Development Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/react-email.md Add a script to your `package.json` to easily start the React Email development server. This command watches for changes in your email templates directory. ```json { "scripts": { "email": "email dev --dir src/emails" } } ``` -------------------------------- ### Deploying Elysia to Cloudflare Workers Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Example of an Elysia application adapted for Cloudflare Workers using the CloudflareAdapter. Requires a wrangler.toml configuration file. ```typescript import { Elysia } from 'elysia' import { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker' export default new Elysia({ adapter: CloudflareAdapter }) .get('/', () => 'Hello Cloudflare!') .compile() ``` ```toml # wrangler.toml name = "elysia-app" main = "src/index.ts" compatibility_date = "2025-06-01" ``` -------------------------------- ### Unit Tests for Elysia App using .handle() Source: https://context7.com/elysiajs/skills/llms.txt Comprehensive unit tests for an Elysia application. It covers basic GET and POST requests, including request handling, response validation, and schema enforcement. Uses Bun's testing utilities. ```typescript // app.test.ts import { describe, expect, it } from 'bun:test' import { treaty } from '@elysiajs/eden' import { app } from './app' describe('API Tests', () => { it('should return hello world', async () => { const res = await app.handle(new Request('http://localhost/')) expect(res.status).toBe(200) expect(await res.text()).toBe('Hello World') }) it('should get user by id', async () => { const res = await app.handle( new Request('http://localhost/user/123') ) const data = await res.json() expect(res.status).toBe(200) expect(data).toEqual({ id: '123', name: 'Test User' }) }) it('should create user with valid body', async () => { const res = await app.handle( new Request('http://localhost/user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', age: 25 }) }) ) expect(res.status).toBe(200) }) it('should reject invalid body', async () => { const res = await app.handle( new Request('http://localhost/user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', age: -5 }) }) ) expect(res.status).toBe(400) }) // Using Eden Treaty for type-safe tests it('should work with Eden', async () => { const api = treaty(app) const { data, error } = await api.user({ id: '456' }).get() expect(error).toBeNull() expect(data?.id).toBe('456') }) }) ``` -------------------------------- ### Define Schema with Description and Detail Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/openapi.md Define request body schemas with descriptions and specify route details like summary and tags. This example shows a username and password schema with a minimum length for the password. ```typescript body: t.Object({ username: t.String(), password: t.String({ minLength: 8, description: 'Password (8+ chars)' }) }, { description: 'Expected username and password' }), detail: { summary: 'Sign in user', tags: ['auth'] } ``` -------------------------------- ### Build for Production Source: https://github.com/elysiajs/skills/blob/main/elysia/references/bun-fullstack-dev-server.md Compiles the project into a single executable binary. ```bash bun build --compile --target bun --outfile server src/index.ts ``` -------------------------------- ### Routing Basics Source: https://github.com/elysiajs/skills/blob/main/elysia/references/route.md Demonstrates different path types including static, dynamic, and wildcard paths, along with their priority. ```APIDOC ## Routing Basics ### Description Defines how to set up routes with static, dynamic, and wildcard paths. ### Path Types - Static: `'/static'` - Exact match. - Dynamic: `'/id/:id'` - Captures a segment. - Wildcard: `'/id/*'` - Captures the rest of the path. ### Path Priority Static paths have higher priority than dynamic paths, which have higher priority than wildcard paths. ### Example ```ts new Elysia() .get('/static', 'static path') .get('/id/:id', 'dynamic path') .get('/id/*', 'wildcard path') ``` ``` -------------------------------- ### Use Context Utilities Source: https://github.com/elysiajs/skills/blob/main/elysia/references/route.md Demonstrates status setting, headers, redirects, cookies, and file responses. ```ts import { redirect, form } from 'elysia' new Elysia().get('/', ({ status, set, form }) => { // Status code (type-safe) status(418, "I'm a teapot") // Set response props set.headers['x-custom'] = 'value' set.status = 418 // legacy, no type inference // Redirect return redirect('https://...', 302) // Cookies (mutable signal, no get/set) cookie.name.value // get cookie.name.value = 'new' // set // FormData response return form({ name: 'Party', images: [file('a.jpg')] }) // Single file return file('document.pdf') }) ``` -------------------------------- ### Compile Elysia App to Binary Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Use 'bun build --compile' for a self-contained executable. This is recommended for production as it eliminates the need for a runtime on the deployment server, reduces memory footprint, and speeds up startup. ```bash bun build \ --compile \ --minify-whitespace \ --minify-syntax \ --target bun \ --outfile server \ src/index.ts ``` ```bash ./server ``` -------------------------------- ### Initialize Elysia with Deno.serve Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/deno.md Use Deno.serve to handle incoming requests by passing the Elysia fetch method. ```typescript import { Elysia } from 'elysia' const app = new Elysia() .get('/', () => 'Hello Elysia') .listen(3000) Deno.serve(app.fetch) ``` -------------------------------- ### Bun Configuration for Preloading Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Configure Bun to preload the instrumentation file using the `preload` option in `bunfig.toml`. ```toml # bunfig.toml preload = ["./src/instrumentation.ts"] ``` -------------------------------- ### Install ElysiaJS Dependencies with pnpm Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/sveltekit.md Manually install necessary dependencies for ElysiaJS, specifically `@sinclair/typebox` and `openapi-types`, using the pnpm package manager. ```bash pnpm add @sinclair/typebox openapi-types ``` -------------------------------- ### Define Elysia Server in Tanstack Start Route Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/tanstack-start.md Configures an Elysia instance within a Tanstack Start route file to handle API requests. ```typescript // src/routes/api.$.ts import { Elysia } from 'elysia' 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 } } }) ``` -------------------------------- ### JWT Authentication Plugin Setup Source: https://context7.com/elysiajs/skills/llms.txt Integrates the JWT plugin for secure token-based authentication. Configure the JWT secret and expiration time. This setup includes routes for login, accessing protected resources, and logout. ```typescript import { Elysia, t } from 'elysia' import { jwt } from '@elysiajs/jwt' const app = new Elysia() .use(jwt({ name: 'jwt', secret: process.env.JWT_SECRET!, exp: '7d' // Token expires in 7 days })) ``` -------------------------------- ### JSX Route Example Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/html.md Standard implementation of a JSX-based route in an Elysia application. ```tsx import React from 'react' import { Elysia } from 'elysia' import { html, Html } from '@elysiajs/html' new Elysia() .use(html()) .get('/', () => ( Hello World

Hello World

)) .listen(3000) ``` -------------------------------- ### Test GET Request Source: https://github.com/elysiajs/skills/blob/main/elysia/references/testing.md Verify route parameters and JSON response structure. ```typescript it('should get user by id', async () => { const app = new Elysia() .get('/user/:id', ({ params: { id } }) => ({ id, name: 'John Doe' })) const res = await app.handle( new Request('http://localhost/user/123') ) const data = await res.json() expect(res.status).toBe(200) expect(data).toEqual({ id: '123', name: 'John Doe' }) }) ``` -------------------------------- ### Production Dockerfile Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Multi-stage Dockerfile for building a standalone binary using Bun and deploying with a distroless image. ```dockerfile # Dockerfile FROM oven/bun:1 AS build WORKDIR /app COPY package.json bun.lock ./ RUN bun install COPY ./src ./src ENV NODE_ENV=production RUN bun build --compile --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 ``` -------------------------------- ### Basic HTML and JSX Usage Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/html.md Initialize the plugin and return HTML strings or JSX elements in route handlers. ```tsx import React from 'react' import { Elysia } from 'elysia' import { html, Html } from '@elysiajs/html' new Elysia() .use(html()) .get( '/html', () => ` Hello World

Hello World

` ) .get('/jsx', () => ( Hello World

Hello World

)) .listen(3000) ``` -------------------------------- ### Production Deployment (Advanced) Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Guidance on deploying instrumented applications to production, focusing on bundling and external dependencies. ```APIDOC ### Production Deployment (Advanced) OpenTelemetry monkey-patches `node_modules`. Exclude instrumented libs from bundling: ```bash bun build --compile --external pg --outfile server src/index.ts ``` Package.json: ```json { "dependencies": { "pg": "^8.15.6" }, "devDependencies": { "@elysiajs/opentelemetry": "^1.2.0", "@opentelemetry/instrumentation-pg": "^0.52.0" } } ``` Production install: ```bash bun install --production ``` Keeps `node_modules` with instrumented libs at runtime. ``` -------------------------------- ### Quick Scaffold ElysiaJS App Source: https://github.com/elysiajs/skills/blob/main/elysia/SKILL.md Use this command to quickly scaffold a new ElysiaJS project. ```bash bun create elysia app ``` -------------------------------- ### Dynamic Paths and Optional Parameters Source: https://github.com/elysiajs/skills/blob/main/elysia/references/route.md Illustrates the usage of dynamic path parameters and how to define optional parameters. ```APIDOC ## Dynamic Paths and Optional Parameters ### Description Shows how to capture and use dynamic segments in paths and how to make parameters optional. ### Dynamic Path Usage - Captures a single dynamic segment: `'/id/:id'` - Captures multiple dynamic segments: `'/id/:id/:name'` ### Optional Parameters Use a question mark `?` after the parameter name to make it optional: `.get('/id/:id?', ...)` ### Example ```ts new Elysia() .get('/id/:id', ({ params: { id } }) => id) .get('/id/:id/:name', ({ params: { id, name } }) => id + ' ' + name) .get('/optional/:id?', ({ params: { id } }) => id) ``` ``` -------------------------------- ### Elysia Behavior Differences Source: https://github.com/elysiajs/skills/blob/main/elysia/references/validation.md Examples illustrating how Elysia handles optional parameters and auto-conversion differently than standard TypeBox. ```typescript .get('/optional', ({ query }) => query, { query: t.Optional( // makes query itself optional t.Object({ name: t.String() }) ) }) ``` ```typescript .get('/:id', ({ id }) => id, { params: t.Object({ id: t.Number() // ✅ Auto-converts to t.Numeric() }), body: t.Object({ id: t.Number() // ❌ NOT converted (stays t.Number()) }) }) // Outside route schema t.Number() // ❌ NOT converted ``` ```typescript .get('/:active', ({ active }) => active, { params: t.Object({ active: t.Boolean() // ✅ Auto-converts to t.BooleanString() }), body: t.Object({ active: t.Boolean() // ❌ NOT converted }) }) ``` -------------------------------- ### Serve Static Files and Directories Source: https://context7.com/elysiajs/skills/llms.txt Serves static assets with custom headers, path prefixes, and SPA fallback support. ```typescript import { Elysia, file } from 'elysia' import { staticPlugin } from '@elysiajs/static' new Elysia() // Serve public folder at /public prefix .use(staticPlugin({ assets: 'public', prefix: '/public', headers: { 'Cache-Control': 'public, max-age=31536000' } })) // Serve uploads folder .use(staticPlugin({ assets: 'uploads', prefix: '/uploads', ignorePatterns: ['*.tmp', '.gitkeep'] })) // Serve single file .get('/favicon.ico', file('public/favicon.ico')) // Serve file with custom headers .get('/download/:filename', ({ params }) => { return new Response(Bun.file(`./downloads/${params.filename}`), { headers: { 'Content-Disposition': `attachment; filename="${params.filename}"` } }) }) // SPA fallback - serve index.html for unmatched routes .use(staticPlugin({ assets: 'dist', prefix: '/', indexHTML: true })) .listen(3000) ``` -------------------------------- ### TypeBox Attribute Constraints Source: https://github.com/elysiajs/skills/blob/main/elysia/references/validation.md Examples of applying JSON Schema 7 attributes to standard TypeBox types for validation constraints. ```typescript // Email format t.String({ format: 'email' }) // Number constraints t.Number({ minimum: 10, maximum: 100 }) // Array constraints t.Array(t.Number(), { minItems: 1, // min items maxItems: 5 // max items }) // Object - allow extra properties t.Object( { x: t.Number() }, { additionalProperties: true } // default: false ) ``` -------------------------------- ### Initialize TypeScript configuration Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nodejs.md Generate the initial tsconfig.json file. ```bash tsc --init ``` -------------------------------- ### Schema Description Example Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/openapi.md Define request body schemas with descriptions and associate them with route details like summary and tags. ```APIDOC ## Schema Description ```typescript body: t.Object({ username: t.String(), password: t.String({ minLength: 8, description: 'Password (8+ chars)' }) }, { description: 'Expected username and password' }), detail: { summary: 'Sign in user', tags: ['auth'] } ``` ``` -------------------------------- ### TypeBox Nested Object Validation Source: https://github.com/elysiajs/skills/blob/main/elysia/SKILL.md Example of defining a TypeBox schema for nested objects, including user details and address. ```typescript body: t.Object({ user: t.Object({ name: t.String(), address: t.Object({ street: t.String(), city: t.String() }) }) }) ``` -------------------------------- ### Custom JWT Namespace Configuration Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/jwt.md Example of configuring the JWT plugin with a custom name to allow multiple JWT instances. ```APIDOC ### name Name to register `jwt` function as. For example, `jwt` function will be registered with a custom name. ```typescript new Elysia() .use( jwt({ name: 'myJWTNamespace', secret: process.env.JWT_SECRETS! }) ) .get('/sign/:name', ({ myJWTNamespace, params }) => { return myJWTNamespace.sign(params) }) ``` Because some might need to use multiple `jwt` with different configs in a single server, explicitly registering the JWT function with a different name is needed. ``` -------------------------------- ### Initialize Elysia with Static Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/references/bun-fullstack-dev-server.md Configures the Elysia server to serve static files with HMR support. ```typescript import { Elysia } from 'elysia' import { staticPlugin } from '@elysiajs/static' new Elysia() .use(await staticPlugin()) // await required for HMR hooks .listen(3000) ``` -------------------------------- ### Run Cloudflare Worker Development Server Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/cloudflare-worker.md Start the local development server for your Cloudflare Worker using the Wrangler CLI. ```bash wrangler dev # http://localhost:8787 ``` -------------------------------- ### Initialize Elysia with Node adapter Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/nodejs.md Configure the Elysia instance to use the Node.js adapter. ```typescript import { Elysia } from 'elysia' import { node } from '@elysiajs/node' const app = new Elysia({ adapter: node() }) .get('/', () => 'Hello Elysia') .listen(3000) ``` -------------------------------- ### Record Database Query with OpenTelemetry Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Use the `record` utility to automatically start, stop, and capture exceptions for a database query span. ```typescript import { record } from '@elysiajs/opentelemetry' .get('', () => { return record('database.query', () => { return db.query('SELECT * FROM users') }) }) ``` -------------------------------- ### Initialize Static Plugin Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/static.md Register the static plugin to serve files from the default public directory. ```typescript import { Elysia } from 'elysia' import { staticPlugin } from '@elysiajs/static' new Elysia() .use(staticPlugin()) .listen(3000) ``` -------------------------------- ### Configure Resource Detectors via Environment Variables Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Set environment variables to specify which resource detectors OpenTelemetry should use for auto-detection. ```bash export OTEL_NODE_RESOURCE_DETECTORS="env,host" # Options: env, host, os, process, serviceinstance, all, none ``` -------------------------------- ### Avoid Passing Context to Controllers Source: https://github.com/elysiajs/skills/blob/main/elysia/patterns/mvc.md Anti-pattern example showing why passing the entire Context object to a controller is discouraged due to type complexity. ```typescript import type { Context } from 'elysia' abstract class Controller { constructor() {} // Don't do this static root(context: Context) { return Service.doStuff(context.stuff) } } ``` -------------------------------- ### ElysiaJS Error Handling with Status Source: https://github.com/elysiajs/skills/blob/main/elysia/SKILL.md Provides an example of handling errors in ElysiaJS by returning a specific status code and message when a user is not found. ```typescript .get('/user/:id', ({ params: { id }, status }) => { const user = findUser(id) // Assuming findUser is defined elsewhere if (!user) { return status(404, 'User not found') } return user }) ``` -------------------------------- ### Run Elysia with Deno CLI Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/deno.md Execute the application using the Deno serve command with watch mode enabled. ```bash deno serve --watch src/index.ts ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/elysiajs/skills/blob/main/elysia/references/deployment.md Commands to build a Docker image for your Elysia application and run it as a container. ```bash docker build -t my-elysia-app . docker run -p 3000:3000 my-elysia-app ``` -------------------------------- ### File Upload Example Source: https://github.com/elysiajs/skills/blob/main/elysia/references/eden.md Handle file uploads by passing a File, File array, FileList, or Blob as the 'image' property in the request body. ```typescript // Accepts: File | File[] | FileList | Blob .image.post({ title: 'Title', image: fileInput.files! }) ``` -------------------------------- ### Basic Elysia CORS Setup Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/cors.md Set up Elysia to accept requests from any origin using the CORS plugin. Ensure the plugin is used before listening. ```typescript import { Elysia } from 'elysia' import { cors } from '@elysiajs/cors' new Elysia().use(cors()).listen(3000) ``` -------------------------------- ### Deploy with Expo Runtime Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/expo.md Use the expo export command to generate server functions for deployment. ```bash expo export # Creates dist/server/_expo/functions/[...slugs]+api.js ``` -------------------------------- ### ElysiaJS Guards for Multiple Routes Source: https://github.com/elysiajs/skills/blob/main/elysia/SKILL.md Applies a guard to multiple routes, in this case, validating the 'id' parameter for both GET and DELETE requests to '/user/:id'. ```typescript .guard({ params: t.Object({ id: t.Number() }) }, app => app .get('/user/:id', ({ params: { id } }) => id) .delete('/user/:id', ({ params: { id } }) => id) ) ``` -------------------------------- ### Initialize Better Auth Source: https://github.com/elysiajs/skills/blob/main/elysia/integrations/better-auth.md Configure the Better Auth instance with a database pool. ```typescript import { betterAuth } from 'better-auth' import { Pool } from 'pg' export const auth = betterAuth({ database: new Pool() }) ``` -------------------------------- ### Basic Usage: Sign and Profile Endpoints Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/jwt.md Demonstrates how to use the JWT plugin to sign a JWT and verify it for user authentication. ```APIDOC ## Basic Usage ```typescript [cookie] import { Elysia } from 'elysia' import { jwt } from '@elysiajs/jwt' const app = new Elysia() .use( jwt({ name: 'jwt', secret: 'Fischl von Luftschloss Narfidort' }) ) .get('/sign/:name', async ({ jwt, params: { name }, cookie: { auth } }) => { const value = await jwt.sign({ name }) auth.set({ value, httpOnly: true, maxAge: 7 * 86400, path: '/profile', }) return `Sign in as ${value}` }) .get('/profile', async ({ jwt, status, cookie: { auth } }) => { const profile = await jwt.verify(auth.value) if (!profile) return status(401, 'Unauthorized') return `Hello ${profile.name}` }) .listen(3000) ``` ``` -------------------------------- ### Get Current OpenTelemetry Span Source: https://github.com/elysiajs/skills/blob/main/elysia/plugins/opentelemetry.md Retrieve the current active span using `getCurrentSpan` for manual attribute setting or manipulation within utility functions. ```typescript import { getCurrentSpan } from '@elysiajs/opentelemetry' function utility() { const span = getCurrentSpan() span.setAttributes({ 'custom.attribute': 'value' }) } ``` -------------------------------- ### Assignment Patterns for State/Decorate Source: https://github.com/elysiajs/skills/blob/main/elysia/references/route.md Illustrates the different ways to assign values when using `.state()` or `.decorate()`. ```APIDOC ## Assignment Patterns for State/Decorate ### Description Covers the various syntaxes for assigning values when using context extension methods like `.state()` and `.decorate()`. ### Patterns 1. **Key-Value**: Assign a single value to a specific key. ```ts .state('key', value) .decorate('logger', loggerInstance) ``` 2. **Object**: Assign multiple key-value pairs at once. ```ts .state({ k1: v1, k2: v2 }) .decorate({ logger: loggerInstance, db: dbConnection }) ``` 3. **Remap Function**: Create new properties based on existing ones or other logic. ```ts .state(({ oldState }) => ({ newState: transform(oldState) })) .decorate(({ request }) => ({ userId: request.headers.get('x-user-id') })) ``` ```