How to Handle Fastio Realtime Events with NestJS
Consuming Fastio real-time events with NestJS enables instant responses to file uploads, modifications, and access events in your workspaces. A NestJS event service connects to Fastio's WebSocket events feed or polls the activity feed to coordinate AI agents. This guide covers project setup, event listeners, controller logic, and production best practices.
Why Integrate Fastio Realtime Events with NestJS?
Fastio provides a WebSocket events feed and a realtime activity feed that can be polled via the REST API at https://api.fast.io/current/. Instead of relying on inbound webhooks, your NestJS application connects directly to stream workspace updates, enabling reactive agent workflows.
NestJS fits cleanly into this architecture. Its modular design, strong TypeScript typing, and built-in dependency injection make it scalable for managing high-volume event streams. Background services can maintain persistent WebSocket connections while injecting application services to process files.
Common use cases include triggering OCR and AI summarization on file uploads, syncing external databases on modifications, or alerting teams to new deliverables. With Fastio's 14-day Business Trial (card required), you can test event-driven integrations on shared workspaces.
Build Reactive Agent Workflows
Set up shared workspaces and real-time event handlers. Start integrating Fastio file event handlers in NestJS today.
Related guides
- How to Build Event-Driven Agent Workflows with Fastio EventsFastio enables event-driven agent workflows the moment a file changes through real-time WebSocket event feeds and...
- How to Process Fastio Events with Apache KafkaStreaming Fastio file changes with Apache Kafka ensures durable, ordered, and scalable event delivery for large-scale...
- How to Implement URL Imports with Fastio APIGuide to how implement url imports with fast api: With Fastio's API, URL imports pull files straight from external...
- How to Process Fastio Events with RabbitMQProcessing Fastio events with RabbitMQ lets you handle file events like uploads and modifications reliably. Direct...
- How to Use the Fastio API for HLS Video StreamingBuilding a video application usually requires chaining together cloud storage and separate transcoding services. The...
- How to Connect the Fastio API to OpenAI AssistantsConnecting Fastio to OpenAI Assistants gives your agents direct access to persistent file workspaces, skipping manual...
More on this subject: Agent Integrations and APIs (96 guides)
Prerequisites
Before starting, ensure you have:
- Node.js 18+ installed
- NestJS CLI:
npm i -g @nestjs/cli - A Fastio account (14-day Business Trial requiring a credit card, or active subscription)
- A scoped, long-lived API key generated from your Fastio account settings
- Basic knowledge of TypeScript and NestJS providers
Create a workspace in your Fastio dashboard and obtain an API key with permissions to read workspace activity and event feeds.
Set Up the NestJS Project
Initialize a new NestJS application and install the required dependencies for WebSockets and HTTP polling:
nest new fastio-event-service
cd fastio-event-service
npm install ws @types/ws axios @nestjs/config
Configure ConfigModule in your app.module.ts to load environment variables securely. Store your Fastio credentials in .env:
FASTIO_API_KEY=your_fastio_scoped_api_key
FASTIO_WORKSPACE_ID=ws_your_workspace_id
Create the Event Consumer Service
Create a dedicated service in NestJS to establish and maintain an outbound WebSocket connection to the Fastio event feed:
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import WebSocket from 'ws';
@Injectable()
export class FastioEventsService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(FastioEventsService.name);
private ws: WebSocket;
onModuleInit() {
this.connect();
}
private connect() {
const apiKey = process.env.FASTIO_API_KEY;
const url = 'wss://api.fast.io/current/events';
this.ws = new WebSocket(url, {
headers: { Authorization: `Bearer ${apiKey}` },
});
this.ws.on('open', () => {
this.logger.log('Connected to Fastio WebSocket events feed');
});
this.ws.on('message', (data: string) => {
const event = JSON.parse(data);
this.handleEvent(event);
});
this.ws.on('close', () => {
this.logger.warn('Connection closed. Reconnecting in 5s...');
setTimeout(() => this.connect(), 5000);
});
}
private handleEvent(event: any) {
this.logger.log(`Received event: ${event.event_type} for file ${event.resource?.name}`);
}
onModuleDestroy() {
this.ws?.close();
}
}
Build the Event Gateway and Controller
You can expose internal endpoints within your NestJS service to query event history or trigger manual synchronization passes against Fastio's REST API.
Use Fastio's realtime activity feed endpoint to retrieve past events if your WebSocket connection experienced downtime:
import { Controller, Get, Query } from '@nestjs/common';
import axios from 'axios';
@Controller('events')
export class EventsController {
@Get('history')
async getRecentActivity(@Query('workspaceId') workspaceId: string) {
const response = await axios.get(
`https://api.fast.io/current/activity?workspace_id=${workspaceId}`,
{ headers: { Authorization: `Bearer ${process.env.FASTIO_API_KEY}` } }
);
return response.data;
}
}
Configure Environment and Scoped Authentication
Fastio uses long-lived, human-granted API keys or PKCE login for agents. Restrict your API key's permissions to the specific workspaces your service monitors.
In production, avoid hardcoding keys. Use secret managers or secure environment variables to inject FASTIO_API_KEY.
Test Locally on Development Workspaces
Because Fastio uses outbound WebSocket connections from your NestJS service to the Fastio server, testing locally does not require public tunnels or ngrok.
Start your NestJS server with npm run start:dev. Upload a test document to your workspace using the Fastio dashboard or CLI. Your terminal will immediately display the event notification.
Deploy to Production
Deploy your NestJS application as a persistent background worker using containers on Kubernetes, ECS, Railway, or Render.
Ensure the worker has steady network access to maintain long-lived WebSocket connections to Fastio. Implement health checks and memory monitoring to verify consistent uptime.
Error Handling and Best Practices
Network disconnects are normal in distributed environments. Implement exponential backoff when reconnecting to Fastio's WebSocket feed.
When reconnecting, query the Fastio activity feed using timestamps to process any events that occurred during the disconnection gap. Fastio retains an append-only audit log and file version history, guaranteeing no operations are lost.
Frequently Asked Questions
How does Fastio stream real-time workspace events?
Fastio provides a WebSocket events feed that pushes real-time notifications for file uploads, updates, deletions, and member actions, along with a pollable activity feed via the REST API.
How do I listen to Fastio events in NestJS?
In NestJS, create an injectable service that establishes an outbound WebSocket connection to the Fastio events feed on module initialization, handling events asynchronously.
What Fastio events can I monitor?
You can monitor events like file creation, file updates, deletions, and workspace member additions across your shared folders.
Do I need a public URL or ngrok to test Fastio events?
No. Because your NestJS service establishes an outbound connection to Fastio's WebSocket feed, you can test directly on localhost without exposing ports or using tunnels.
How do I catch up on missed events after a disconnect?
Poll Fastio's realtime activity feed or inspect the append-only audit log via the REST API using your last processed timestamp to process missed updates.
Related Resources
Build Reactive Agent Workflows
Set up shared workspaces and real-time event handlers. Start integrating Fastio file event handlers in NestJS today.