cd..blog

Full-Stack AI: Koa, Firebase, & OpenAI with TypeScript

const published = "Mar 14, 2026, 10:36 PM";const readTime = 5 min;
koafirebaseopenaitypescriptfullstack-ai
Explore integrating Koa, Firebase, and OpenAI API using TypeScript to build a robust, AI-powered backend. Learn practical setup, authentication, and content generation.

Full-Stack AI: Koa, Firebase, & OpenAI with TypeScript

Building modern web applications often involves integrating diverse services to deliver rich, intelligent experiences. This post demonstrates how to combine the lightweight Koa framework, the powerful Firebase platform, and the intelligent OpenAI API within a single TypeScript application.

Architecture Overview

Our application will leverage Koa.js as the backend server, handling API requests and business logic. Firebase will provide robust authentication (Auth) and a flexible NoSQL database (Firestore). OpenAI's API will be integrated for dynamic content generation, such as creating AI-powered responses or ideas. TypeScript ensures type safety and enhances developer experience across all layers.

Setting Up Koa with TypeScript

Koa.js is a minimalist Node.js framework, offering a smaller footprint and a powerful middleware system. We'll use it to create our API endpoints.

First, initialize your project and install necessary dependencies:

npm init -y
npm install koa @koa/router koa-bodyparser firebase-admin openai dotenv
npm install -D typescript ts-node-dev @types/node @types/koa @types/koa__router @types/koa-bodyparser @types/firebase-admin

Create a tsconfig.json:

{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "rootDir": "./src",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Your basic Koa server (src/server.ts) will look like this:

// src/server.ts
import Koa from 'koa';
import Router from '@koa/router';
import bodyParser from 'koa-bodyparser';
import dotenv from 'dotenv';

dotenv.config();

const app = new Koa();
const router = new Router();

app.use(bodyParser());

router.get('/', async (ctx) => {
  ctx.body = 'Welcome to the Koa, Firebase, OpenAI integrated app!';
});

app.use(router.routes()).use(router.allowedMethods());

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Integrating Firebase (Auth & Firestore)

Firebase provides a comprehensive suite of backend services. We'll use Firebase Admin SDK to interact with Firestore for data storage and Firebase Authentication for securing our API endpoints.

  1. Service Account: Generate a service account key from your Firebase project settings (Project settings > Service accounts) and save its JSON content to a .env variable, e.g., FIREBASE_SERVICE_ACCOUNT_KEY="{"type": "service_account", ...}". This key allows your backend to securely access Firebase resources.
  2. Initialize SDK: In src/server.ts, initialize the Firebase Admin SDK.
// ... (imports)
import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';
import { getAuth } from 'firebase-admin/auth';

// ... (dotenv.config())

// --- Firebase Initialization ---
const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_KEY || '{}');
if (!serviceAccount || Object.keys(serviceAccount).length === 0) {
  console.error("Firebase service account key not found. Exiting.");
  process.exit(1);
}

initializeApp({
  credential: cert(serviceAccount),
});

const db = getFirestore();
const auth = getAuth();

// ... (Koa app setup)

Firebase Authentication Middleware

To protect routes, we'll create a Koa middleware that verifies Firebase ID tokens sent in the Authorization header.

// ... (Firebase initialization)

// --- Middleware for Firebase Authentication ---
const authenticate = async (ctx: Koa.Context, next: Koa.Next) => {
  const authHeader = ctx.request.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.status = 401;
    ctx.body = { error: 'Authentication required' };
    return;
  }

  const idToken = authHeader.split('Bearer ')[1];
  try {
    const decodedToken = await auth.verifyIdToken(idToken);
    ctx.state.user = decodedToken; // Attach user info to ctx.state
    await next();
  } catch (error) {
    console.error('Error verifying Firebase ID token:', error);
    ctx.status = 401;
    ctx.body = { error: 'Invalid or expired token' };
  }
};

// ... (Koa router setup)

Integrating OpenAI API

OpenAI's API allows programmatic access to their powerful AI models. We'll use the official Node.js SDK to generate text.

  1. API Key: Obtain an API key from the OpenAI platform and store it in your .env file: OPENAI_API_KEY=sk-....
  2. Initialize Client: Initialize the OpenAI client in src/server.ts.
// ... (Firebase imports)
import { OpenAI } from 'openai';

// ... (Firebase initialization)

// --- OpenAI Initialization ---
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// ... (Koa app setup)

Putting It All Together: An AI Idea Generator

Let's create a protected endpoint /generate-idea that requires authentication, uses OpenAI to generate a startup idea based on a user prompt, and saves the idea to Firestore.

// ... (authenticate middleware)

// --- Routes ---

router.get('/', async (ctx) => {
  ctx.body = 'Welcome to the Koa, Firebase, OpenAI integrated app!';
});

// Protected endpoint: Generates an idea using OpenAI and saves to Firestore
router.post('/generate-idea', authenticate, async (ctx) => {
  const { prompt } = ctx.request.body as { prompt: string };
  const userId = ctx.state.user.uid; // User ID from authenticated token

  if (!prompt) {
    ctx.status = 400;
    ctx.body = { error: 'Prompt is required' };
    return;
  }

  try {
    // 1. Generate content with OpenAI
    const completion = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo', // Consider 'gpt-4o' for advanced capabilities
      messages: [
        { role: 'system', content: 'You are a creative assistant that generates startup ideas.' },
        { role: 'user', content: `Generate a concise startup idea based on this theme: ${prompt}` },
      ],
      max_tokens: 150,
    });

    const generatedIdea = completion.choices[0].message.content;

    if (!generatedIdea) {
      ctx.status = 500;
      ctx.body = { error: 'Failed to generate idea from OpenAI' };
      return;
    }

    // 2. Save to Firestore
    const docRef = await db.collection('user_ideas').add({
      userId,
      prompt,
      generatedIdea,
      timestamp: new Date().toISOString(),
    });

    ctx.status = 201;
    ctx.body = {
      message: 'Idea generated and saved successfully',
      idea: generatedIdea,
      docId: docRef.id,
    };
  } catch (error) {
    console.error('Error generating or saving idea:', error);
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
  }
});

// ... (app.use(router.routes()))

Best Practices & Considerations

  • Environment Variables: Always use .env files and dotenv for sensitive keys (Firebase service account, OpenAI API key). Never hardcode them.
  • Error Handling: Implement robust try...catch blocks and return informative error messages. Consider a global error handling middleware for Koa.
  • Security: Ensure your Firebase security rules are properly configured to prevent unauthorized data access. Validate all incoming API requests.
  • Rate Limiting: OpenAI and Firebase APIs have rate limits. Implement client-side and server-side rate limiting to manage usage.
  • Scalability: Koa is highly performant. Firebase and OpenAI are managed services designed for scale, making this a robust stack for growth.

Conclusion

By integrating Koa, Firebase, and OpenAI with TypeScript, developers can build powerful, intelligent, and scalable full-stack applications. This architecture provides a solid foundation for secure authentication, flexible data storage, and dynamic AI capabilities, empowering you to create the next generation of web experiences.