Build high-performance APIs with Elysia and Bun runtime in Google Antigravity
# Elysia Bun Framework for Google Antigravity
Elysia is a performant framework built for Bun runtime. This guide covers patterns for Google Antigravity IDE and Gemini 3.
## Application Setup
```typescript
// src/index.ts
import { Elysia, t } from 'elysia';
import { cors } from '@elysiajs/cors';
import { swagger } from '@elysiajs/swagger';
import { jwt } from '@elysiajs/jwt';
import { cookie } from '@elysiajs/cookie';
const app = new Elysia()
.use(cors())
.use(swagger({ documentation: { info: { title: 'API', version: '1.0.0' } } }))
.use(jwt({ name: 'jwt', secret: process.env.JWT_SECRET! }))
.use(cookie())
.state('version', '1.0.0')
.decorate('db', database)
.get('/', () => 'Hello Elysia')
.listen(3000);
console.log(`Server running at ${app.server?.hostname}:${app.server?.port}`);
```
## Type-Safe Routes
```typescript
// src/routes/users.ts
import { Elysia, t } from 'elysia';
import { db } from '../db';
export const userRoutes = new Elysia({ prefix: '/users' })
.get('/', async () => {
const users = await db.user.findMany({ select: { id: true, email: true, name: true } });
return users;
})
.get('/:id', async ({ params: { id }, error }) => {
const user = await db.user.findUnique({ where: { id } });
if (!user) return error(404, 'User not found');
return user;
}, { params: t.Object({ id: t.String() }) })
.post('/', async ({ body, set }) => {
const user = await db.user.create({ data: body });
set.status = 201;
return user;
}, {
body: t.Object({
email: t.String({ format: 'email' }),
name: t.String({ minLength: 2 }),
password: t.String({ minLength: 8 }),
}),
})
.put('/:id', async ({ params: { id }, body, error }) => {
const user = await db.user.update({ where: { id }, data: body });
if (!user) return error(404, 'User not found');
return user;
}, {
params: t.Object({ id: t.String() }),
body: t.Object({
email: t.Optional(t.String({ format: 'email' })),
name: t.Optional(t.String({ minLength: 2 })),
}),
})
.delete('/:id', async ({ params: { id }, set }) => {
await db.user.delete({ where: { id } });
set.status = 204;
}, { params: t.Object({ id: t.String() }) });
```
## Authentication Plugin
```typescript
// src/plugins/auth.ts
import { Elysia, t } from 'elysia';
import { jwt } from '@elysiajs/jwt';
export const authPlugin = new Elysia({ name: 'auth' })
.use(jwt({ name: 'jwt', secret: process.env.JWT_SECRET! }))
.derive(async ({ jwt, cookie: { auth }, error }) => {
const token = auth.value;
if (!token) return { user: null };
const payload = await jwt.verify(token);
if (!payload) return { user: null };
return { user: payload as { id: string; email: string } };
})
.macro(({ onBeforeHandle }) => ({
isAuth(enabled: boolean) {
if (!enabled) return;
onBeforeHandle(({ user, error }) => {
if (!user) return error(401, 'Unauthorized');
});
},
}));
// Usage
app.use(authPlugin).get('/protected', ({ user }) => user, { isAuth: true });
```
## WebSocket Support
```typescript
// src/websocket.ts
import { Elysia, t } from 'elysia';
const connections = new Map<string, any>();
export const wsRoutes = new Elysia()
.ws('/ws', {
body: t.Object({ type: t.String(), payload: t.Any() }),
open(ws) {
const id = crypto.randomUUID();
ws.data = { id };
connections.set(id, ws);
ws.send(JSON.stringify({ type: 'connected', id }));
},
message(ws, { type, payload }) {
switch (type) {
case 'broadcast':
connections.forEach((conn) => {
if (conn !== ws) conn.send(JSON.stringify({ type: 'message', payload }));
});
break;
case 'ping':
ws.send(JSON.stringify({ type: 'pong' }));
break;
}
},
close(ws) {
connections.delete(ws.data.id);
},
});
```
## Error Handling
```typescript
// src/error.ts
import { Elysia } from 'elysia';
export const errorPlugin = new Elysia({ name: 'error' })
.onError(({ code, error, set }) => {
console.error(error);
switch (code) {
case 'VALIDATION':
set.status = 400;
return { error: 'Validation failed', details: error.all };
case 'NOT_FOUND':
set.status = 404;
return { error: 'Not found' };
default:
set.status = 500;
return { error: 'Internal server error' };
}
});
```
## Best Practices
1. **Type Inference**: Leverage Elysia's end-to-end type safety
2. **Plugins**: Create reusable plugins for cross-cutting concerns
3. **Validation**: Use t.Object for compile-time and runtime validation
4. **Derive**: Add computed properties to context
5. **Macros**: Create custom route modifiers
6. **WebSockets**: Built-in WS support with type safety
Google Antigravity's Gemini 3 understands Elysia patterns and generates type-safe APIs.This Elysia prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their elysia implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Elysia projects, consider mentioning your framework version, coding style, and any specific libraries you're using.