Full-Stack AI: NestJS, Bun Cloud, DigitalOcean, and Hugging Face
Modern web development demands performance, scalability, and seamless integration with intelligent services. This post demonstrates how to build a robust, AI-powered backend using a powerful combination: NestJS for structured APIs, Bun for blazing-fast runtime and tooling, Hugging Face Inference API for AI capabilities, and deployment to Bun Cloud complemented by DigitalOcean infrastructure.
Architectural Synergy
Our architecture leverages NestJS to provide a modular, scalable API layer. Bun acts as the performant JavaScript runtime and package manager, accelerating development and execution. Hugging Face provides access to state-of-the-art AI models, while Bun Cloud offers a serverless deployment target, and DigitalOcean can host supplementary services like databases.
Setting Up NestJS with Bun
NestJS, a progressive Node.js framework, builds on TypeScript and combines elements of OOP, FP, and FRP. Bun is an all-in-one JavaScript runtime, package manager, and bundler, offering significant speed improvements over Node.js and npm/yarn.
To start, create a new NestJS project using Bun:
// Install NestJS CLI globally if you haven't already
bun add -g @nestjs/cli
// Create a new NestJS project using Bun as the package manager
nest new ai-backend --package-manager bun
cd ai-backend
// Start the development server
bun dev
Next, generate a module, service, and controller to encapsulate our AI logic:
nest g module ai
nest g service ai
nest g controller ai
Integrating Hugging Face Inference API
Hugging Face offers a vast repository of pre-trained machine learning models accessible via their Inference API. This allows us to integrate advanced AI capabilities like text generation or sentiment analysis into our application without managing complex ML infrastructure.
First, obtain an API token from your Hugging Face settings page. Then, create a service to interact with the API. We'll use fetch for simplicity.
// src/ai/ai.service.ts
import { Injectable } from '@nestjs/common';
interface HuggingFaceInferenceResponse {
generated_text: string;
}
@Injectable()
export class AiService {
private readonly HUGGING_FACE_API_KEY = process.env.HUGGING_FACE_API_KEY;
private readonly MODEL_URL = 'https://api-inference.huggingface.co/models/gpt2'; // Example model
async generateText(prompt: string): Promise<string> {
if (!this.HUGGING_FACE_API_KEY) {
throw new Error('Hugging Face API key is not configured.');
}
const response = await fetch(this.MODEL_URL, {
headers: {
Authorization: `Bearer ${this.HUGGING_FACE_API_KEY}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({ inputs: prompt }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Hugging Face API error: ${response.status} - ${JSON.stringify(errorData)}`);
}
const data: HuggingFaceInferenceResponse[] = await response.json();
return data[0]?.generated_text || 'No text generated.';
}
}
Expose this functionality via a controller:
// src/ai/ai.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { AiService } from './ai.service';
interface GenerateTextDto {
prompt: string;
}
@Controller('ai')
export class AiController {
constructor(private readonly aiService: AiService) {}
@Post('generate')
async generate(@Body() { prompt }: GenerateTextDto) {
const generatedText = await this.aiService.generateText(prompt);
return { text: generatedText };
}
}
Remember to add AiService and AiController to AiModule providers and controllers arrays respectively.
Deployment with Bun Cloud and DigitalOcean
Bun Cloud provides a serverless platform optimized for Bun applications, offering exceptional performance and ease of deployment. DigitalOcean offers a comprehensive suite of cloud services, perfect for hosting databases, object storage, or other microservices that complement your Bun Cloud application.
To deploy your NestJS application to Bun Cloud, ensure your package.json has a start script that Bun can execute (e.g., "start": "nest start"). Then, from your project root, simply run:
bun deploy
Bun Cloud automatically detects your framework and deploys your application. For persistent data, you might provision a DigitalOcean Managed PostgreSQL Database and connect your NestJS application to it using environment variables managed by Bun Cloud.
TypeScript Best Practices
Throughout this integration, TypeScript is paramount for maintaining code quality and developer productivity. Define clear interfaces for API request/response payloads, service method parameters, and environment variables. This ensures type safety across your application, from the NestJS backend to external API calls.
// Example for environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
HUGGING_FACE_API_KEY: string;
DATABASE_URL?: string;
}
}
}
Conclusion
By combining NestJS's structured approach, Bun's performance, Hugging Face's AI capabilities, and the seamless deployment provided by Bun Cloud with DigitalOcean's robust ecosystem, developers can build highly efficient and intelligent applications. This stack offers a modern, scalable foundation for the next generation of web services. Experiment with different Hugging Face models and explore DigitalOcean's offerings to expand your application's capabilities.