Self-hosted MongoDB cannot be connected from Bolt's WebContainer during development — the mongoose and mongodb Node.js drivers require raw TCP connections that WebContainers block. Your app will work after deploying to Netlify or Vercel, but cannot connect to self-hosted MongoDB in the Bolt preview. Better alternatives: MongoDB Atlas with its HTTP Data API, or Supabase PostgreSQL which works natively in Bolt.
Self-Hosted MongoDB in Bolt.new: The TCP Problem and Real Solutions
MongoDB is the world's most popular NoSQL database. If you're trying to connect a Bolt.new app to a self-hosted MongoDB instance — running on your own server, a VPS, Docker container, or a cloud VM — you will hit a fundamental architectural limitation: Bolt's WebContainer cannot make raw TCP connections. Both the official mongodb driver and the mongoose ODM use TCP to communicate with MongoDB servers, and the WebContainer's virtual networking layer blocks TCP socket creation entirely. Your code appears to run, packages install correctly, but the connection either hangs or throws a connection timeout error during development.
This is not a bug in your code or your MongoDB setup. It is a structural constraint of running Node.js inside a browser tab. The connection failure only happens in the Bolt preview. Once you deploy your app to Netlify, Vercel, or any traditional Node.js hosting environment, the same mongoose or mongodb code connects to your MongoDB server without any changes. The production environment runs real Node.js with real networking, so TCP connections work normally.
The practical implication: you cannot develop a self-hosted MongoDB integration iteratively in Bolt's preview. You can write the code and prompt the AI to build features, but you must deploy to test whether the database connection actually works. This is a significant development friction point. The community solution is to use MongoDB Atlas instead of self-hosted MongoDB — Atlas provides an HTTP-based Data API that works in the WebContainer — or to switch to Supabase PostgreSQL, which uses HTTP via PostgREST and works natively in Bolt. This tutorial shows both paths: setting up the code that works post-deployment, and the smarter alternatives.
Integration method
Self-hosted MongoDB cannot be reached from Bolt's WebContainer during development because the mongoose and mongodb drivers use raw TCP connections, which WebContainers block. The connection will work after deploying to Netlify or Vercel where a real Node.js runtime executes. If you want database connectivity during Bolt development, use MongoDB Atlas with its HTTP-based Data API or switch to Supabase PostgreSQL. This tutorial covers: the WebContainer TCP limitation, Next.js API route setup that works post-deployment, Prisma with MongoDB adapter, and alternative recommendations.
Prerequisites
- A MongoDB instance (self-hosted or MongoDB Atlas) with connection details
- MongoDB Atlas account if using the recommended Atlas Data API approach (free M0 cluster)
- A Bolt.new project using Next.js for API routes
- Understanding that self-hosted MongoDB connections only work after deployment to Netlify or Vercel
- For Atlas Data API: Data API enabled in Atlas project settings with an API key generated
Step-by-step guide
Understand the WebContainer TCP Limitation
Understand the WebContainer TCP Limitation
Before writing any code, it is important to understand exactly what will and will not work in Bolt's preview when connecting to self-hosted MongoDB. Bolt's WebContainer virtualizes a Node.js runtime inside the browser using WebAssembly. The networking layer maps HTTP requests to the browser's fetch API and WebSocket connections to the browser's WebSocket API. However, raw TCP socket operations — which is how both the mongodb Node.js driver and mongoose connect to MongoDB servers — are not supported. When your app starts and mongoose calls mongoose.connect('mongodb://...'), the underlying driver attempts to open a TCP socket to the MongoDB port (default 27017). This TCP operation is silently rejected by the WebContainer, resulting in a 'MongooseServerSelectionError: connect ECONNREFUSED' or a timeout after 30 seconds. This limitation applies specifically to the Bolt WebContainer preview. The code itself is not wrong. The same mongoose connection string and code work perfectly on: - Netlify (after npm run build + deploy) - Vercel (after npm run build + deploy) - Render, Railway, Fly.io, or any VPS - Your local machine running Node.js outside of Bolt If you want to test database operations during development in Bolt, you have two viable options: (1) use MongoDB Atlas with its HTTP Data API, which communicates over HTTPS instead of TCP, or (2) use Supabase PostgreSQL, which uses HTTP via PostgREST. Both work in the WebContainer. If you need self-hosted MongoDB specifically for production (self-hosted gives you more control over data residency, costs, and schema), write the mongoose code in Bolt and test it by deploying — there is no workaround that makes TCP work in the WebContainer.
1// This is what fails in Bolt's WebContainer:2// import mongoose from 'mongoose';3// await mongoose.connect('mongodb://localhost:27017/mydb');4// Error: MongooseServerSelectionError: connect ECONNREFUSED56// This works in WebContainer (Atlas HTTP Data API):7// await fetch('https://data.mongodb-api.com/app/data-abc/endpoint/data/v1/action/findOne', {8// method: 'POST',9// headers: { 'api-key': process.env.ATLAS_API_KEY, 'Content-Type': 'application/json' },10// body: JSON.stringify({ dataSource: 'Cluster0', database: 'mydb', collection: 'users', filter: {} })11// });1213// The mongoose code below works correctly AFTER deployment to Netlify/Vercel.Pro tip: If you absolutely need self-hosted MongoDB and must test in Bolt: deploy to Netlify in one click (Settings → Applications → Netlify → Publish), test the database connection, fix issues, and republish. Use Bolt for UI and code iteration; Netlify for database testing.
Expected result: You understand the WebContainer TCP constraint and have decided either to proceed with self-hosted MongoDB (testing post-deployment) or to use MongoDB Atlas Data API (works in preview).
Set Up mongoose with Connection Caching for Next.js
Set Up mongoose with Connection Caching for Next.js
If you are using self-hosted MongoDB and will test after deployment, set up the standard Next.js mongoose connection pattern. Next.js API routes are serverless functions — each function invocation may run in a separate process, and without connection caching, each request would open a new database connection, quickly exhausting MongoDB's connection pool limit. The solution is a global connection cache: store the mongoose connection promise in a global variable that persists between hot reloads during development and between Lambda invocations in the same container during production. The pattern uses a global variable (global.mongoose) to hold the cached connection. This is the approach recommended by Next.js in their official MongoDB example. Your MongoDB URI format: for self-hosted MongoDB, it follows the pattern mongodb://[username:password@]host[:port]/[database]. For local development, mongodb://localhost:27017/mydatabase. For a remote server, mongodb://username:password@your-server-ip:27017/mydatabase. For MongoDB Atlas (cloud), it looks like mongodb+srv://username:password@cluster.mongodb.net/mydatabase — the srv format uses DNS SRV records which also go over TCP, so Atlas TCP also fails in WebContainer. Use Atlas Data API instead for Bolt preview testing.
Set up mongoose for MongoDB in my Next.js project. Create lib/mongodb.ts with a cached connection pattern using a global variable to prevent connection exhaustion in serverless environments. Read MONGODB_URI from environment variables. Export a connectDB function that resolves when connected. Create a .env file with a placeholder MONGODB_URI. Handle connection errors gracefully and log connection status.
Paste this in Bolt.new chat
1// lib/mongodb.ts2import mongoose from 'mongoose';34const MONGODB_URI = process.env.MONGODB_URI!;56if (!MONGODB_URI) {7 throw new Error('MONGODB_URI environment variable is not defined');8}910interface MongooseCache {11 conn: typeof mongoose | null;12 promise: Promise<typeof mongoose> | null;13}1415declare global {16 // eslint-disable-next-line no-var17 var mongoose: MongooseCache | undefined;18}1920const cached: MongooseCache = global.mongoose || { conn: null, promise: null };21global.mongoose = cached;2223export async function connectDB(): Promise<typeof mongoose> {24 if (cached.conn) return cached.conn;2526 if (!cached.promise) {27 cached.promise = mongoose28 .connect(MONGODB_URI, { bufferCommands: false })29 .then((m) => {30 console.log('MongoDB connected');31 return m;32 });33 }3435 cached.conn = await cached.promise;36 return cached.conn;37}Pro tip: Add ?retryWrites=true&w=majority to your MongoDB Atlas connection string for production reliability. For self-hosted MongoDB, set the socketTimeoutMS option to a reasonable value (45000ms) to prevent hanging connections.
Expected result: lib/mongodb.ts is set up with connection caching. MONGODB_URI is in .env with your MongoDB connection string. Note: the connection will time out in Bolt's preview — this is expected.
Define Mongoose Models and Create API Routes
Define Mongoose Models and Create API Routes
With the connection utility ready, define your mongoose schemas and models. A mongoose model describes the shape of your MongoDB documents — the fields, their types, validation rules, and default values. Keep models in a models/ directory, one file per collection. Models should only be defined once per process, so use the pattern: module.exports = mongoose.models.ModelName || mongoose.model('ModelName', schema) to prevent 'Cannot overwrite model once compiled' errors during Next.js hot reloading. API routes in Next.js are the correct place to connect and query MongoDB. Each API route is a serverless function that runs server-side — it has access to server-only environment variables, can make database connections, and doesn't run in the browser. Never import mongoose or call connectDB() in client components, React hooks, or client-side utilities. Only in app/api/ files. For standard CRUD operations, the pattern is: call connectDB() at the top of each handler, then use your mongoose model to execute queries. Mongoose queries return promises, so await them inside try/catch blocks. Return appropriate HTTP status codes — 200 for GET success, 201 for POST (created), 400 for validation errors, 404 for not found, 500 for server errors.
Create a mongoose User model in models/User.ts with fields: name (String, required), email (String, required, unique, lowercase), role (String, enum: user/admin, default: user), createdAt (Date, default: Date.now). Create Next.js API routes at app/api/users/route.ts (GET all users, POST create user) and app/api/users/[id]/route.ts (GET by id, PUT update, DELETE). Each route must call connectDB() from lib/mongodb.ts before querying. Return proper HTTP status codes and error messages.
Paste this in Bolt.new chat
1// models/User.ts2import mongoose, { Schema, Document } from 'mongoose';34export interface IUser extends Document {5 name: string;6 email: string;7 role: 'user' | 'admin';8 createdAt: Date;9}1011const UserSchema = new Schema<IUser>({12 name: { type: String, required: [true, 'Name is required'] },13 email: {14 type: String,15 required: [true, 'Email is required'],16 unique: true,17 lowercase: true,18 match: [/^\S+@\S+\.\S+$/, 'Invalid email format'],19 },20 role: { type: String, enum: ['user', 'admin'], default: 'user' },21 createdAt: { type: Date, default: Date.now },22});2324export const User =25 mongoose.models.User ||26 mongoose.model<IUser>('User', UserSchema);2728// app/api/users/route.ts29import { NextResponse } from 'next/server';30import { connectDB } from '@/lib/mongodb';31import { User } from '@/models/User';3233export async function GET() {34 try {35 await connectDB();36 const users = await User.find({}).sort({ createdAt: -1 }).limit(100);37 return NextResponse.json(users);38 } catch (error: unknown) {39 const e = error as { message: string };40 return NextResponse.json({ error: e.message }, { status: 500 });41 }42}4344export async function POST(request: Request) {45 try {46 await connectDB();47 const body = await request.json();48 const user = new User(body);49 await user.save();50 return NextResponse.json(user, { status: 201 });51 } catch (error: unknown) {52 const e = error as { message: string; code?: number };53 const status = e.code === 11000 ? 409 : 400;54 return NextResponse.json({ error: e.message }, { status });55 }56}Pro tip: Mongoose error code 11000 means a duplicate key violation — a document with the same unique field value already exists. Return a 409 Conflict status instead of 400 for duplicate key errors so the frontend can show a helpful 'email already in use' message.
Expected result: The User model is defined, and API routes for CRUD operations are in place. The routes work correctly after deployment but will throw connection timeout errors in the Bolt preview — this is expected due to WebContainer TCP limitations.
Alternative: Use MongoDB Atlas Data API (Recommended for Bolt Preview)
Alternative: Use MongoDB Atlas Data API (Recommended for Bolt Preview)
If you want database operations to work during Bolt development — not just post-deployment — MongoDB Atlas with the Data API is the right choice. Atlas is MongoDB's managed cloud service, and it provides an HTTP REST API (the Data API) that lets you perform CRUD operations over HTTPS without any MongoDB driver or TCP connection. This is architecturally identical to how REST databases work, making it fully compatible with Bolt's WebContainer. To enable the Atlas Data API: log into cloud.mongodb.com, select your project, click on 'Data API' in the left sidebar (under 'Data Services'), enable Data API for your cluster, and create an API key. You will get a Data API endpoint URL (looks like https://data.mongodb-api.com/app/data-xxxxx/endpoint/data/v1) and an API key. All requests include the api-key header and a JSON body specifying the dataSource (cluster name), database, collection, and operation. The Data API supports the most common operations: findOne, find, insertOne, insertMany, updateOne, updateMany, replaceOne, deleteOne, deleteMany, and aggregate. This covers 95% of real app needs. It is slightly slower than a direct driver connection due to the HTTP overhead, but for most apps this difference is imperceptible. The major benefit for Bolt development is immediate: you can test and iterate on data operations in the Bolt preview without deploying.
Set up MongoDB Atlas Data API integration (HTTP-based, works in Bolt preview). Create lib/atlas.ts with an atlasRequest function that wraps fetch() calls to the Atlas Data API. Read ATLAS_DATA_API_URL, ATLAS_API_KEY, ATLAS_DATA_SOURCE, and ATLAS_DATABASE from environment variables. Export helper functions: findDocuments(collection, filter, projection), findOne(collection, filter), insertOne(collection, document), updateOne(collection, filter, update), deleteOne(collection, filter). Create a .env file with placeholder values for all four variables.
Paste this in Bolt.new chat
1// lib/atlas.ts2const DATA_API_URL = process.env.ATLAS_DATA_API_URL!;3const API_KEY = process.env.ATLAS_API_KEY!;4const DATA_SOURCE = process.env.ATLAS_DATA_SOURCE || 'Cluster0';5const DATABASE = process.env.ATLAS_DATABASE!;67interface AtlasRequestBody {8 dataSource: string;9 database: string;10 collection: string;11 [key: string]: unknown;12}1314async function atlasRequest<T>(action: string, body: Omit<AtlasRequestBody, 'dataSource' | 'database'>): Promise<T> {15 const response = await fetch(`${DATA_API_URL}/action/${action}`, {16 method: 'POST',17 headers: {18 'api-key': API_KEY,19 'Content-Type': 'application/json',20 },21 body: JSON.stringify({ dataSource: DATA_SOURCE, database: DATABASE, ...body }),22 });2324 if (!response.ok) {25 const text = await response.text();26 throw new Error(`Atlas Data API ${action} failed: ${text}`);27 }2829 return response.json() as Promise<T>;30}3132export const atlas = {33 findDocuments: <T>(collection: string, filter = {}, projection?: object) =>34 atlasRequest<{ documents: T[] }>('find', { collection, filter, projection }),3536 findOne: <T>(collection: string, filter: object) =>37 atlasRequest<{ document: T | null }>('findOne', { collection, filter }),3839 insertOne: <T>(collection: string, document: T) =>40 atlasRequest<{ insertedId: string }>('insertOne', { collection, document }),4142 updateOne: (collection: string, filter: object, update: object) =>43 atlasRequest<{ matchedCount: number; modifiedCount: number }>('updateOne', {44 collection, filter, update,45 }),4647 deleteOne: (collection: string, filter: object) =>48 atlasRequest<{ deletedCount: number }>('deleteOne', { collection, filter }),49};Pro tip: Atlas Data API has a 1,000 requests-per-second limit on the free M0 tier. For development, this is more than sufficient. If you need higher throughput in production, migrate to using the native MongoDB driver after deploying to a real Node.js environment.
Expected result: The Atlas Data API client works in the Bolt preview — you can test all CRUD operations without deploying. API calls go through the fetch() function over HTTPS and complete successfully.
Deploy and Test Self-Hosted MongoDB Connection
Deploy and Test Self-Hosted MongoDB Connection
After building your application logic in Bolt, deploy to Netlify or Bolt Cloud to test the self-hosted MongoDB connection in a real Node.js environment. Self-hosted MongoDB deployment requires your MongoDB server to be accessible from the internet with the correct firewall rules, authentication, and connection string. For Netlify deployment: connect your Bolt project to Netlify via Settings → Applications → Netlify. After your first deploy, go to Netlify Dashboard → Site Settings → Environment Variables and add MONGODB_URI with your production MongoDB connection string. Trigger a redeploy after setting the environment variable. Important network requirements for self-hosted MongoDB: your MongoDB server must allow inbound connections from Netlify's or Vercel's serverless function IP ranges. Netlify runs functions on AWS Lambda (us-east-1 primarily); Vercel also uses AWS Lambda. You cannot use specific IP allowlists with serverless platforms since function IPs change dynamically — you must either open MongoDB to all IPs (0.0.0.0/0) with strong authentication, use VPN/tunnel, or use MongoDB Atlas which does not have this problem. Test the deployment: after setting MONGODB_URI in Netlify, your API routes should connect successfully. Check Netlify's function logs for connection errors. Common issues: MongoDB server not accessible from Netlify's network, authentication credentials wrong, firewall blocking port 27017, or TLS/SSL misconfiguration. For production, always enable TLS on your MongoDB server.
Help me prepare my Next.js app with MongoDB for Netlify deployment. Create a netlify.toml configuration file with build command 'npm run build', publish directory '.next', and Node.js version 20. Make sure all Next.js API routes properly handle errors and return JSON responses even when the database connection fails, so the app doesn't show a blank error page. Add a health check endpoint at /api/health that tests the MongoDB connection and returns {status: 'ok', database: 'connected'} or {status: 'error', database: 'disconnected'}.
Paste this in Bolt.new chat
1# netlify.toml2[build]3 command = "npm run build"4 publish = ".next"56[build.environment]7 NODE_VERSION = "20"89[[plugins]]10 package = "@netlify/plugin-nextjs"Pro tip: For self-hosted MongoDB on a VPS (DigitalOcean, AWS EC2, etc.), use MongoDB's built-in TLS with a certificate. Open port 27017 to 0.0.0.0/0 in your firewall but require authentication with a strong username/password combination. Never run MongoDB without authentication on a publicly accessible server.
Expected result: After deploying to Netlify and setting MONGODB_URI in environment variables, your API routes successfully connect to MongoDB. GET /api/health returns {status: 'ok', database: 'connected'}.
Common use cases
Migrate Existing App from Self-Hosted to Atlas-Compatible Code
You have an existing app using self-hosted MongoDB and want to move it into Bolt for continued development. The first step is writing Bolt-compatible API routes using mongoose that will work after deployment, then either keeping self-hosted MongoDB for production or migrating to Atlas. This use case focuses on writing the right code structure.
Set up a MongoDB connection using mongoose in my Next.js project. Create a lib/mongodb.ts that exports a cached mongoose connection using the MONGODB_URI environment variable. Create an app/api/users/route.ts that gets all users (GET) and creates a new user (POST) using a User mongoose model with name, email, and createdAt fields. I understand the connection will only work after deployment, not in Bolt's preview.
Copy this prompt to try it in Bolt.new
Full CRUD API with Mongoose Models
Build a complete REST API with Next.js API routes backed by MongoDB via mongoose. Define mongoose schemas for your data models, implement GET/POST/PUT/DELETE endpoints, and set up connection caching so each serverless function invocation reuses the connection pool. Deploy to Netlify to test end-to-end.
Build a product catalog API with MongoDB and mongoose. Create a Product schema with: name (required string), description (string), price (number), category (string), inventory (number), images (string array), createdAt (date). Create REST API routes at /api/products: GET (list with optional category filter), POST (create), GET /api/products/[id] (single), PUT /api/products/[id] (update), DELETE /api/products/[id] (delete). Use connection caching pattern in lib/mongodb.ts. Use MONGODB_URI from env.
Copy this prompt to try it in Bolt.new
Switch to MongoDB Atlas Data API (Recommended for Bolt Development)
MongoDB Atlas provides an HTTP-based Data API that works perfectly in Bolt's WebContainer — no TCP, no driver required, just fetch() calls to a REST endpoint. If you are starting fresh or willing to migrate, this is strongly recommended over self-hosted for Bolt development. Atlas free tier (M0 cluster) provides 512MB storage at no cost.
Connect my Bolt.new app to MongoDB Atlas using the Atlas Data API (HTTP-based, not the mongoose driver). Create a lib/atlas.ts that exports an atlasQuery function using fetch() to call the Atlas Data API endpoint from ATLAS_DATA_API_URL, with ATLAS_API_KEY and ATLAS_DATA_SOURCE from environment variables. Create API routes at /api/products using atlasQuery for findOne, find, insertOne, updateOne, deleteOne operations. This should work in the Bolt preview without deployment.
Copy this prompt to try it in Bolt.new
Troubleshooting
MongooseServerSelectionError: connect ECONNREFUSED or connection timeout in Bolt preview
Cause: This is the expected WebContainer TCP limitation. mongoose and the mongodb driver attempt TCP connections to MongoDB's port (27017), which WebContainers block entirely. This error is not caused by a misconfigured connection string.
Solution: This error only occurs in Bolt's WebContainer preview. For development testing, switch to MongoDB Atlas Data API (HTTP-based) which works in the preview. For self-hosted MongoDB, deploy to Netlify or Bolt Cloud and test there — the same mongoose code works in a real Node.js environment.
OverwriteModelError: Cannot overwrite User model once compiled
Cause: Next.js hot module replacement re-executes module files during development, trying to redefine mongoose models that are already registered in the mongoose model registry.
Solution: Use the pattern mongoose.models.User || mongoose.model('User', UserSchema) to check if the model already exists before registering it. This is required for all mongoose models in Next.js projects.
1// In every model file:2export const User =3 mongoose.models.User ||4 mongoose.model<IUser>('User', UserSchema);5// Never just: mongoose.model('User', UserSchema)MONGODB_URI environment variable not found, process.env.MONGODB_URI is undefined
Cause: Next.js server-side environment variables are read at startup. The .env file may not be saved, the variable may be misspelled, or the dev server needs a restart after editing .env.
Solution: Verify the .env file has MONGODB_URI= followed by your connection string without quotes. Restart the Bolt dev server (stop and restart the terminal process) after editing .env since Next.js caches env variables at startup. Do NOT add NEXT_PUBLIC_ prefix to MONGODB_URI — it must be server-only.
1# .env — correct format (no quotes needed):2MONGODB_URI=mongodb://username:password@your-server:27017/mydb3# OR for Atlas:4MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydbAtlas Data API returns 401 Unauthorized
Cause: The ATLAS_API_KEY is incorrect, expired, or the Data API has not been enabled for the Atlas cluster.
Solution: Go to cloud.mongodb.com → Data API → verify Data API is enabled for your cluster. Regenerate the API key if needed. Ensure ATLAS_DATA_API_URL exactly matches the endpoint shown in Atlas (it includes a unique app ID like data-xxxxxx). Also verify ATLAS_DATA_SOURCE matches your cluster name exactly.
Best practices
- Use MongoDB Atlas Data API instead of self-hosted MongoDB if you want to test database operations in Bolt's WebContainer preview — it communicates over HTTPS and bypasses the TCP limitation
- Always use the connection caching pattern for mongoose in Next.js to prevent connection pool exhaustion in serverless environments
- Never add NEXT_PUBLIC_ prefix to MONGODB_URI — connection strings contain credentials and must be server-side only
- Define mongoose models with the mongoose.models.X || mongoose.model('X', schema) pattern to prevent OverwriteModelError during Next.js hot reloads
- Handle MongoDB error code 11000 (duplicate key) separately from other errors and return 409 Conflict rather than 500 Internal Server Error
- For production self-hosted MongoDB, always enable TLS/SSL and require authentication — never expose an unauthenticated MongoDB port publicly
- Consider Supabase PostgreSQL as an alternative to MongoDB for Bolt projects — it uses HTTP via PostgREST, works natively in WebContainers, and gives you SQL query power with a free managed tier
Alternatives
MongoDB Atlas is the managed cloud version of MongoDB with an HTTP Data API that works in Bolt's WebContainer preview, making it strongly preferred over self-hosted for Bolt development.
PostgreSQL via Supabase or Neon communicates over HTTP in WebContainers, works in the Bolt preview, and offers strong SQL querying capabilities as an alternative to MongoDB's document model.
MySQL via PlanetScale's HTTP API works in WebContainers and provides a familiar relational database with a generous free tier and branching workflow.
Firestore is a document database like MongoDB but with an HTTP-based JavaScript SDK that works in Bolt's WebContainer preview, making it a viable NoSQL alternative.
Frequently asked questions
Why does mongoose fail in Bolt's WebContainer but work after deployment?
Bolt's WebContainer runs Node.js inside a browser tab using WebAssembly. Browser security prevents raw TCP socket connections, which is how mongoose communicates with MongoDB servers. After deploying to Netlify or Vercel, the code runs in real Node.js with full networking capabilities, so the same mongoose connection string works correctly. This is not a code problem — it is a fundamental architectural constraint of the browser-based runtime.
Can I use Prisma with MongoDB in Bolt.new?
Yes, with a caveat. Prisma supports MongoDB via its MongoDB adapter (datasource db { provider = 'mongodb', url = env('MONGODB_URI') }). Prisma generates and runs a query engine that ultimately uses the MongoDB driver, which means the same TCP limitation applies — Prisma + MongoDB will fail in the Bolt preview. Prisma with Neon or PlanetScale (HTTP-based adapters) works in the preview. For MongoDB specifically, Prisma works after deployment but not during Bolt development.
Is MongoDB Atlas different from self-hosted MongoDB for Bolt integration?
For Bolt development purposes, yes — significantly different. The standard Atlas driver connection (mongodb+srv://...) uses TCP and fails in the WebContainer just like self-hosted MongoDB. However, Atlas provides an additional HTTP-based Data API that communicates over HTTPS using fetch() and works perfectly in the WebContainer. Use the Atlas Data API endpoint (not the driver connection string) for Bolt development. After deployment to a real Node.js server, you can use either the driver or the Data API.
Should I use MongoDB or Supabase PostgreSQL for a new Bolt.new project?
For new Bolt projects, Supabase PostgreSQL is strongly recommended over MongoDB. Supabase uses HTTP via PostgREST for all database operations, works natively in the WebContainer preview, includes authentication, storage, and edge functions in the same platform, and has native Bolt integration. MongoDB makes sense if you have existing MongoDB data or specifically need a document database's flexible schema. For most web apps, PostgreSQL's relational model and Supabase's Bolt integration offer a smoother development experience.
Can I use Bolt.new to build a MongoDB dashboard or admin panel?
Yes, with the Atlas Data API approach for development. Build the UI and API routes in Bolt using the Atlas Data API client, test in the Bolt preview, then deploy to Netlify. After deployment, you can switch to the native mongoose driver if you prefer — both work in production. For self-hosted MongoDB management, build the UI in Bolt and test via rapid deploy cycles to Netlify since preview testing is not possible.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation