How do I add a database to my AI-generated app?
Using a Backend-as-a-Service
Supabase and Firebase are popular because they handle database hosting, authentication, and APIs out of the box. You create a project, get connection credentials, and then use their client libraries in your app.
For example, with Supabase, you can use the supabase-js library to query your Postgres database directly from your frontend (with row-level security) or from serverless functions. Firebase offers Firestore, a NoSQL database with real-time updates.
These services have free tiers suitable for development and small apps. They also provide dashboards to manage data and users.
- Supabase: Postgres with real-time and auth.
- Firebase: Firestore (NoSQL) with real-time and auth.
- MongoDB Atlas: Free 500MB cluster.
- PlanetScale: MySQL with branching (free tier limited).
Connecting to Your App
If your AI-built app is a static site, you'll need to add a backend to securely connect to the database. You can use serverless functions (on Vercel/Netlify) or a separate backend server (on Render/Railway).
In your code, you'll typically store database credentials in environment variables and use an ORM or query builder to interact with the database. For example, Prisma works well with Postgres and MySQL.
If you're using a full-stack framework like Next.js, you can create API routes that handle database queries, keeping credentials safe on the server.
Common mistakes
- Embedding database credentials directly in frontend code, exposing them to users.
- Choosing a database that doesn't fit your data model (e.g., using NoSQL for highly relational data).
- Forgetting to set up backups or security rules, leaving your data vulnerable.
