Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
3e6af08
Configurable Http Plugin
heyitsaamir Jan 16, 2026
8ab16d1
Fix lint
heyitsaamir Jan 16, 2026
4f53f18
Remove configurable-http-plugin for HttpServer.
heyitsaamir Jan 24, 2026
660e392
Use Adapter
heyitsaamir Jan 20, 2026
38972de
Fix
heyitsaamir Jan 20, 2026
f5230f5
Jwt Validation
heyitsaamir Jan 20, 2026
b57ffe8
HttpServer
heyitsaamir Jan 20, 2026
7acbcbc
Logger
heyitsaamir Jan 22, 2026
ff52956
Fix
heyitsaamir Jan 22, 2026
fee1672
Fix tests
heyitsaamir Jan 23, 2026
235c202
Update
heyitsaamir Dec 10, 2025
a66ba33
Separate activity sending from HTTP transport layer
heyitsaamir Dec 16, 2025
15855e3
Revert
heyitsaamir Jan 15, 2026
d6582a9
Revert
heyitsaamir Jan 15, 2026
6795d82
Configurable Http Plugin
heyitsaamir Jan 16, 2026
65d71ab
Fix lint
heyitsaamir Jan 16, 2026
8555f2b
Remove configurable-http-plugin for HttpServer.
heyitsaamir Jan 20, 2026
638f876
Use Adapter
heyitsaamir Jan 20, 2026
3d2ec46
HttpServer
heyitsaamir Jan 20, 2026
38c274f
Remove paths
heyitsaamir Jan 23, 2026
9ada3a0
Fix examples
heyitsaamir Jan 24, 2026
df71c55
Fix readme
heyitsaamir Jan 24, 2026
a4c63e2
Fix
heyitsaamir Jan 24, 2026
fec351f
package-lock.json
heyitsaamir Jan 24, 2026
0f2c0df
nextjs -> fastify
heyitsaamir Jan 24, 2026
6df7ce3
fix ci
heyitsaamir Jan 24, 2026
8556c4a
fix bot builder
heyitsaamir Jan 24, 2026
42c7614
Fix tests
heyitsaamir Jan 24, 2026
df6cf81
Fix
heyitsaamir Jan 24, 2026
1d3651b
Add build essential
heyitsaamir Jan 24, 2026
e6e08a0
Revert express
heyitsaamir Jan 24, 2026
b5139d0
add test for tab
heyitsaamir Jan 25, 2026
95d91e9
fix tests
heyitsaamir Jan 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/http-adapters/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PORT=3978
CLIENT_ID=your-client-id
CLIENT_SECRET=your-client-secret
27 changes: 27 additions & 0 deletions examples/http-adapters/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# HTTP Adapter Examples

This example shows how to integrate teams.ts with different HTTP frameworks using custom adapters.

## What's an Adapter?

An adapter bridges your HTTP framework with teams.ts. You create your server, pass it to the adapter, and teams.ts adds the `/api/messages` bot endpoint to your existing app.

## Examples

- **[express/](./express/)** - Hook your own Express server with the built-in Express adapter
- **[hono/](./hono/)** - Build a custom adapter and manage the lifecycle yourself
- **[fastify/](./fastify/)** - Build a custom adapter and let App manage its lifecycle

## Running

```bash
npm install
cp .env.example .env

# Run an example
npm run dev:express
npm run dev:hono
npm run dev:fastify
```

All examples start on `http://localhost:3978` with `/api/messages` as the bot endpoint.
30 changes: 30 additions & 0 deletions examples/http-adapters/express/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import 'dotenv/config';
import { app, httpServer } from './teams-app';

const port = parseInt(process.env.PORT || '3978', 10);

async function main() {
console.log('Starting Express server with Teams bot integration...\n');

// Initialize teams.ts app - this adds /api/messages to your Express app
await app.initialize();

// Start your Express server
await new Promise<void>((resolve, reject) => {
httpServer.listen(port, () => resolve());
httpServer.once('error', reject);
});

console.log(`✓ Server ready on http://localhost:${port}`);
console.log(`\nYour Express routes:`);
console.log(` GET / - Homepage`);
console.log(` GET /health - Health check`);
console.log(` GET /api/users - Users API`);
console.log(` POST /api/messages - Teams bot endpoint (added by teams.ts)`);
console.log(`\nOpen http://localhost:${port} in your browser!`);
}

main().catch((err) => {
console.error('Failed to start:', err);
process.exit(1);
});
50 changes: 50 additions & 0 deletions examples/http-adapters/express/teams-app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import http from 'http';
import express from 'express';
import { App, ExpressAdapter } from '@microsoft/teams.apps';

// 1. Create your existing Express app with routes
export const expressApp = express();
export const httpServer = http.createServer(expressApp);

// Add your custom routes
expressApp.get('/health', (_req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});

expressApp.get('/api/users', (_req, res) => {
res.json({
users: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
});
});

expressApp.get('/', (_req, res) => {
res.send(`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is cute, should we do the same in other languages/samples?

<html>
<body>
<h1>Express + teams.ts</h1>
<p>Your Express server is running with a Teams bot!</p>
<ul>
<li><a href="/health">Health Check</a></li>
<li><a href="/api/users">API: Users</a></li>
<li><strong>/api/messages</strong> - Teams bot endpoint</li>
</ul>
</body>
</html>
`);
});

// 2. Create Express adapter with your existing server
export const adapter = new ExpressAdapter(httpServer);

// 3. Create teams.ts app with the adapter
export const app = new App({
httpAdapter: adapter
});

// 4. Handle incoming messages
app.on('message', async ({ send, activity }) => {
await send(`Echo from Express server: ${activity.text}`);
});
97 changes: 97 additions & 0 deletions examples/http-adapters/fastify/fastify-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import fastify, { FastifyInstance } from 'fastify';
import { IHttpAdapter, IRouteConfig } from '@microsoft/teams.apps/dist/http/adapter';

/**
* Fastify adapter for HttpServer
*
* Handles Fastify-specific HTTP framework concerns:
* - Fastify app creation and initialization
* - Route registration via Fastify routing
* - Request/response data extraction and sending
* - Server lifecycle management
*
* Usage:
* const adapter = new FastifyAdapter();
* const app = new App({ httpAdapter: adapter });
* await app.initialize();
* await app.start(3978);
*/
export class FastifyAdapter implements IHttpAdapter {
protected fastify: FastifyInstance;
protected isUserProvidedInstance: boolean;

constructor(instance?: FastifyInstance) {
this.isUserProvidedInstance = !!instance;
this.fastify = instance || fastify({ logger: true });
}

/**
* Get the Fastify instance for adding custom routes/plugins
*/
get instance(): FastifyInstance {
return this.fastify;
}

/**
* Register a route with Fastify
*/
registerRouteHandler(config: IRouteConfig): void {
const { path, handler } = config;

// Register with Fastify
this.fastify.route({
method: 'POST',
url: path,
handler: async (request, reply) => {
try {
// Provide helpers to the handler
await handler({
extractRequestData: () => ({
body: request.body as any,
headers: request.headers as Record<string, string>
}),
sendResponse: (response) => {
reply.status(response.status).send(response.body);
}
});
} catch (err) {
reply.status(500).send({ error: 'Internal server error' });
}
}
});
}

/**
* Initialize the adapter
* No initialization needed - Fastify will call ready() automatically when listen() is called
*/
async initialize(): Promise<void> {
// No initialization needed for Fastify
// Routes must be registered before calling listen()
// Fastify will automatically call ready() when listen() is invoked
}

/**
* Start the server
* Throws if instance was user-provided
*/
async start(port: number): Promise<void> {
if (this.isUserProvidedInstance) {
throw new Error(
'Cannot call start() when Fastify instance was provided by user. ' +
'User should call fastify.listen() directly.'
);
}

await this.fastify.listen({ port, });
}

/**
* Stop the server
*/
async stop(): Promise<void> {
if (!this.isUserProvidedInstance) {
await this.fastify.close();
}
}
}
28 changes: 28 additions & 0 deletions examples/http-adapters/fastify/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import 'dotenv/config';
import { app } from './teams-app';

const port = parseInt(process.env.PORT || '3978', 10);

async function main() {
console.log('Starting Fastify server with Teams bot integration...\n');

// In this case, we're choosing to use a Fastify server to run the app
// app.start() will initialize the app and start the Fastify server
//
// Alternatively, we could have used app.initialize() and then started
// the Fastify server separately with adapter.instance.listen()
await app.start(port);

console.log(`✓ Server ready on http://localhost:${port}`);
console.log(`\nYour Fastify routes:`);
console.log(` GET / - Homepage`);
console.log(` GET /health - Health check`);
console.log(` GET /api/users - Users API`);
console.log(` POST /api/messages - Teams bot endpoint (added by teams.ts)`);
console.log(`\nOpen http://localhost:${port} in your browser!`);
}

main().catch((err) => {
console.error('Failed to start:', err);
process.exit(1);
});
48 changes: 48 additions & 0 deletions examples/http-adapters/fastify/teams-app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { App } from '@microsoft/teams.apps';
import { FastifyAdapter } from './fastify-adapter';

// 1. Create Fastify adapter
export const adapter = new FastifyAdapter();

// Get the Fastify instance to add custom routes
const fastify = adapter.instance;

// 2. Add your custom routes
fastify.get('/health', async (_request, reply) => {
return reply.send({ status: 'healthy', timestamp: new Date().toISOString() });
});

fastify.get('/api/users', async (_request, reply) => {
return reply.send({
users: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
});
});

fastify.get('/', async (_request, reply) => {
return reply.type('text/html').send(`
<html>
<body>
<h1>Fastify + teams.ts</h1>
<p>Your Fastify server is running with a Teams bot!</p>
<ul>
<li><a href="/health">Health Check</a></li>
<li><a href="/api/users">API: Users</a></li>
<li><strong>/api/messages</strong> - Teams bot endpoint</li>
</ul>
</body>
</html>
`);
});

// 3. Create teams.ts app with the adapter
export const app = new App({
httpAdapter: adapter,
});

// 4. Handle incoming messages
app.on('message', async ({ send, activity }) => {
await send(`Echo from Fastify server: ${activity.text}`);
});
88 changes: 88 additions & 0 deletions examples/http-adapters/hono/hono-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Hono, Context } from 'hono';
import { IHttpAdapter, IRouteConfig } from '@microsoft/teams.apps/dist/http/adapter';

/**
* Hono adapter for HttpServer
*
* Wraps an existing Hono app to add Teams bot routes.
* Server lifecycle (start/stop) is managed by the user externally.
*
* Usage:
* const hono = new Hono();
* const app = new App({ httpAdapter: new HonoAdapter(hono) });
* await app.initialize();
* // Start your Hono server separately with serve() or @hono/node-server
*/
export class HonoAdapter implements IHttpAdapter {
protected hono: Hono;

/**
* Create adapter with your existing Hono app
* @param hono Your Hono app with your custom routes
*/
constructor(hono: Hono) {
this.hono = hono;
}

/**
* Register a POST route handler with Hono
* All routes are POST-only (Teams bot protocol uses POST)
*/
registerRouteHandler(config: IRouteConfig): void {
const { path, handler } = config;

// Convert handler to Hono handler signature
const honoHandler = async (c: Context) => {
try {
// Parse JSON body
const body = await c.req.json().catch(() => ({}));
const headers = Object.fromEntries(c.req.raw.headers.entries());

let responseData: { status: number; body: any } | undefined;

// Provide helpers to the handler
await handler({
extractRequestData: () => ({
body,
headers
}),
sendResponse: (response) => {
responseData = response;
}
});

// Send the response
if (responseData) {
return c.json(responseData.body, responseData.status as any);
} else {
return c.json({ error: 'No response provided' }, 500);
}
} catch (err) {
console.error('Hono handler error:', err);
return c.json({ error: 'Internal server error' }, 500);
}
};

// Register as POST route
this.hono.post(path, honoHandler);
}

/**
* Serve static files from a directory
* Note: For production, consider using Hono's built-in static middleware
* or a CDN for better performance
*/
serveStatic(path: string, directory: string): void {
// Hono's static file serving
this.hono.get(`${path}/*`, async (c) => {
const filePath = c.req.path.replace(path, directory);
try {
const fs = await import('fs/promises');
const content = await fs.readFile(filePath);
return c.body(content);
} catch {
return c.notFound();
}
});
}
}
Loading
Loading