Skip to main content
RapidDev - Software Development Agency
lovable-integrationEdge Function Integration

How to Integrate Lovable with MongoDB Atlas

MongoDB retired the Atlas Data API in September 2025, so older guides that call it no longer work. To connect Lovable to MongoDB Atlas now, store your Atlas connection string in Cloud Secrets, create an Edge Function that uses the official MongoDB Node.js driver through an npm import, and call that function from your Lovable frontend. Never connect from the browser.

What you'll learn

  • Why the Atlas Data API no longer works and what replaces it
  • How to store your Atlas connection string securely in Lovable Cloud → Secrets
  • How to write a Deno Edge Function that uses the MongoDB Node.js driver
  • How to call that Edge Function from your Lovable React frontend
  • When to choose MongoDB Atlas over Lovable's native Supabase PostgreSQL database
Book a free consultation
4.9Clutch rating ⭐
1,000+Happy partners
20+Countries served
200+Team members
Intermediate11 min read45 minutesDatabaseLast updated October 2026RapidDev Engineering Team
TL;DR

MongoDB retired the Atlas Data API in September 2025, so older guides that call it no longer work. To connect Lovable to MongoDB Atlas now, store your Atlas connection string in Cloud Secrets, create an Edge Function that uses the official MongoDB Node.js driver through an npm import, and call that function from your Lovable frontend. Never connect from the browser.

Quick facts about this guide
FactValue
ToolMongoDB Atlas
CategoryDatabase
MethodEdge Function Integration
DifficultyIntermediate
Time required45 minutes
Last updatedOctober 2026

Connect Lovable to MongoDB Atlas for document-based data storage

MongoDB Atlas is the world's most popular cloud document database, offering a flexible schema model that is fundamentally different from the relational tables in Lovable's native Supabase PostgreSQL. While Supabase excels at structured, normalized data with predictable shapes — user records, subscription plans, order line items — MongoDB Atlas shines when your data is semi-structured or hierarchical: product catalogs with variable attributes, content management systems with nested blocks, IoT telemetry payloads, or any scenario where every record can have a different shape without ALTER TABLE migrations.

Lovable does not have a native connector for MongoDB Atlas. Instead, the integration follows Lovable's standard pattern for authenticated external services: your Atlas connection string lives in Cloud → Secrets, and all database calls run inside a Supabase Edge Function on Deno that uses the official MongoDB Node.js driver through an npm: import. The older Atlas Data API (a REST interface) was retired by MongoDB on 30 September 2025, so the driver is now the supported route.

The trade-off compared to Lovable's native Supabase is significant: you lose AI-assisted schema generation, auto-created RLS policies, real-time subscriptions, and the natural language database operations that make Lovable's built-in database so productive. However, if your team already has data in MongoDB Atlas or your application requires MongoDB's specific querying capabilities — aggregation pipelines, geospatial queries, full-text search with Atlas Search — this integration pattern gives you a working bridge between Lovable's frontend and your existing Atlas cluster.

Important: the Atlas Data API no longer works

If you followed an older guide (including the previous version of this page) and now see errors from data.mongodb-api.com, the Data API and HTTPS Endpoints were shut down by MongoDB on 30 September 2025. Move the logic into an Edge Function that uses the MongoDB driver, or put a small API layer in front of Atlas.

Current method: MongoDB driver in a Lovable Edge Function

  1. In Atlas, create a database user with least privilege and copy the SRV connection string.
  2. In Atlas Network Access, allow the Edge Function to connect (Edge Functions do not have fixed IPs, so most teams allow access with strong credentials, or use a private API layer).
  3. In Lovable, add MONGODB_URI to Cloud Secrets.
  4. Prompt Lovable: 'Create an Edge Function called mongo-proxy that imports MongoClient from npm:mongodb, reads MONGODB_URI from secrets, reuses one client across requests, and exposes find, insertOne and updateOne for the orders collection with input validation.'
  5. Call the function from React with supabase.functions.invoke and handle errors in the UI.

Integration method

Edge Function Integration

MongoDB Atlas has no native Lovable connector, so all database operations run in a Supabase Edge Function that uses the official MongoDB Node.js driver (npm:mongodb). Your Atlas connection string is stored encrypted in Cloud → Secrets and read with Deno.env.get(), so credentials never reach the browser.

Prerequisites

  • A Lovable account with an active Lovable Cloud project
  • A MongoDB Atlas account with a cluster created (free M0 tier is sufficient for getting started)
  • An Atlas database user with only the permissions your app needs
  • Your cluster's SRV connection string (Atlas → Connect → Drivers)
  • Your MongoDB database name and collection names ready

Step-by-step guide

1

Create a least-privilege Atlas user and copy the connection string

Log in to MongoDB Atlas at cloud.mongodb.com and open your cluster. In Database Access, click 'Add New Database User', choose password authentication and give the user only the roles your app needs (for example readWrite on one database instead of Atlas admin). Then click 'Connect' on your cluster, choose 'Drivers' and copy the SRV connection string. It looks like mongodb+srv://<user>:<password>@cluster0.abcde.mongodb.net/. Replace <user> and <password> with the database user you just created. In Network Access, allow the Edge Function to reach the cluster. Supabase Edge Functions run on distributed infrastructure without a fixed outbound IP, so most teams allow access from anywhere (0.0.0.0/0) and rely on a strong, least-privilege database user, or put a small private API layer in front of Atlas when the network must stay closed.

Pro tip: If you previously used the Atlas Data API, remove its old credentials from Cloud Secrets: they stopped working when MongoDB shut the service down on 30 September 2025.

Expected result: You have a database user with least privilege, an SRV connection string that includes that user, and network access that lets the Edge Function connect.

2

Store the connection string in Cloud → Secrets

In Lovable, click the '+' icon next to the Preview label to open the Cloud panel, then open the 'Secrets' tab. Click 'Add new secret' and add: - Name: MONGODB_URI — Value: the full SRV connection string from step 1 - Name: MONGODB_DB — Value: your database name (for example 'production') Secrets are encrypted, only readable from Edge Functions and never sent to the browser or committed to GitHub. Never paste the connection string into a React component or a prompt that writes it into frontend code.

Pro tip: The secret name must exactly match the Deno.env.get() call in your Edge Function, including capitalization.

Expected result: MONGODB_URI and MONGODB_DB appear in Cloud → Secrets with masked values.

3

Create the mongo-proxy Edge Function with the MongoDB driver

Ask Lovable to create an Edge Function that imports MongoClient from npm:mongodb, connects once and reuses the client across requests, and exposes only the operations your app needs. Restrict which collections and operations the frontend can call, validate input, and require a signed-in user for writes. The code below is a template for an orders collection with find, insertOne and updateOne.

Lovable Prompt

Create an Edge Function called mongo-proxy that imports MongoClient from npm:mongodb, reads MONGODB_URI and MONGODB_DB from secrets, reuses one client across requests, and exposes find, insertOne and updateOne for the orders collection with input validation. Require a signed-in Supabase user for insertOne and updateOne. Include CORS headers.

Paste this in Lovable chat

supabase/functions/mongo-proxy/index.ts
1// supabase/functions/mongo-proxy/index.ts
2import { MongoClient, ObjectId } from "npm:mongodb@6";
3import { createClient } from "npm:@supabase/supabase-js@2";
4
5const corsHeaders = {
6 "Access-Control-Allow-Origin": "*",
7 "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
8};
9
10// One client per Edge Function instance, reused across requests
11const client = new MongoClient(Deno.env.get("MONGODB_URI")!);
12const db = client.db(Deno.env.get("MONGODB_DB")!);
13const ALLOWED = new Set(["orders"]);
14
15Deno.serve(async (req) => {
16 if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
17
18 try {
19 const { action, collection, filter = {}, doc, update, limit = 20 } = await req.json();
20 if (!ALLOWED.has(collection)) {
21 return Response.json({ error: "Collection not allowed" }, { status: 400, headers: corsHeaders });
22 }
23
24 // Writes require a signed-in Supabase user
25 let userId: string | null = null;
26 if (action !== "find") {
27 const supabase = createClient(
28 Deno.env.get("SUPABASE_URL")!,
29 Deno.env.get("SUPABASE_ANON_KEY")!,
30 { global: { headers: { Authorization: req.headers.get("Authorization") ?? "" } } }
31 );
32 const { data } = await supabase.auth.getUser();
33 if (!data.user) return Response.json({ error: "Unauthorized" }, { status: 401, headers: corsHeaders });
34 userId = data.user.id;
35 }
36
37 const col = db.collection(collection);
38 if (action === "find") {
39 const docs = await col.find(filter).limit(Math.min(Number(limit), 100)).toArray();
40 return Response.json({ documents: docs }, { headers: corsHeaders });
41 }
42 if (action === "insertOne") {
43 const result = await col.insertOne({ ...doc, createdBy: userId, createdAt: new Date() });
44 return Response.json({ insertedId: result.insertedId }, { headers: corsHeaders });
45 }
46 if (action === "updateOne") {
47 const id = new ObjectId(String(filter._id));
48 const result = await col.updateOne({ _id: id, createdBy: userId }, { $set: update });
49 return Response.json({ modified: result.modifiedCount }, { headers: corsHeaders });
50 }
51 return Response.json({ error: "Unknown action" }, { status: 400, headers: corsHeaders });
52 } catch (err) {
53 console.error("mongo-proxy error", (err as Error).message);
54 return Response.json({ error: "Database request failed" }, { status: 500, headers: corsHeaders });
55 }
56});

Pro tip: Keep the allow-list of collections in the function. Never let the frontend pass arbitrary collection names or raw aggregation pipelines.

Expected result: The mongo-proxy function appears under supabase/functions/mongo-proxy/index.ts, deploys to Lovable Cloud and shows as active in Cloud → Edge Functions.

4

Call the Edge Function from your Lovable frontend

Use supabase.functions.invoke so the user's session token is sent automatically. Wrap the call in a small hook with loading and error states, and show a friendly message when the function returns an error instead of a blank screen.

Lovable Prompt

Create a hook called useOrders in src/hooks/useOrders.ts that calls the mongo-proxy Edge Function with supabase.functions.invoke (action 'find', collection 'orders') and returns { orders, loading, error }. Then build an Orders page that lists the orders in a table with loading and error states.

Paste this in Lovable chat

src/hooks/useOrders.ts
1// src/hooks/useOrders.ts
2import { useEffect, useState } from "react";
3import { supabase } from "@/integrations/supabase/client";
4
5export function useOrders(filter: Record<string, unknown> = {}) {
6 const [orders, setOrders] = useState<Record<string, unknown>[]>([]);
7 const [loading, setLoading] = useState(true);
8 const [error, setError] = useState<string | null>(null);
9 const filterKey = JSON.stringify(filter);
10
11 useEffect(() => {
12 let cancelled = false;
13 setLoading(true);
14 supabase.functions
15 .invoke("mongo-proxy", { body: { action: "find", collection: "orders", filter: JSON.parse(filterKey) } })
16 .then(({ data, error }) => {
17 if (cancelled) return;
18 if (error) setError(error.message);
19 else setOrders(data.documents ?? []);
20 setLoading(false);
21 });
22 return () => {
23 cancelled = true;
24 };
25 }, [filterKey]);
26
27 return { orders, loading, error };
28}

Pro tip: Use JSON.stringify(filter) as the effect dependency so the list re-fetches when the filter content changes.

Expected result: The Orders page renders documents from your Atlas orders collection.

5

Test the integration and verify security

Publish the app and open the Orders page. If data does not load, open Cloud → Logs for the mongo-proxy function. Then open your browser's developer tools: you should only see calls to your Edge Function URL (functions/v1/mongo-proxy), never your Atlas connection string, user name or cluster host. Finally, try a write while signed out: the function should return 401. That confirms writes are protected.

Expected result: Reads work, signed-out writes return 401, and no Atlas credentials appear in browser network requests.

Common use cases

Build a product catalog with variable attributes

A product catalog where different product types have completely different attribute sets — electronics have voltage and connectivity specs, clothing has sizes and materials, food has nutritional data — is a natural fit for MongoDB's flexible document model. Each product document can carry exactly the fields it needs without empty columns or JSON workarounds in a relational schema.

Lovable Prompt

Create an Edge Function called 'get-products' that fetches documents from my MongoDB Atlas 'products' collection through the mongo-proxy Edge Function. It should accept optional query parameters for category filtering and return the results as JSON. Then build a product listing page that calls this function and displays each product with its name, price, image, and any additional attributes from the document.

Copy this prompt to try it in Lovable

Store and retrieve user-generated content with nested structure

Blog posts, knowledge base articles, or any content with nested sections, tags, embedded media references, and author metadata are easier to model as MongoDB documents than as normalized relational rows. A single document can contain the entire article structure, making reads fast and avoiding multi-table joins.

Lovable Prompt

Create Edge Functions for a simple CMS: 'create-article' that saves a new article document to my MongoDB 'articles' collection, 'list-articles' that returns a summary list (title, slug, publishedAt, author), and 'get-article' that retrieves a single article by slug. Build a public blog page that lists articles and a detail page that renders individual articles.

Copy this prompt to try it in Lovable

Migrate legacy MongoDB data to a new Lovable app

If your existing application stores data in MongoDB Atlas and you are rebuilding the frontend in Lovable, this integration lets you access your existing data immediately without a schema migration. You can read from Atlas, display the data in your new Lovable UI, and plan a gradual migration to Supabase PostgreSQL over time if needed.

Lovable Prompt

I have an existing MongoDB Atlas collection called 'customers' with fields: name, email, company, plan, createdAt, and a nested 'usage' object. Create an Edge Function that queries this collection with pagination (limit 20 per page) and a search by name or email. Build an admin dashboard page that displays this customer list with search and pagination controls.

Copy this prompt to try it in Lovable

Troubleshooting

Errors that mention data.mongodb-api.com, or an 'api-key' header that is rejected

Cause: The code still calls the Atlas Data API, which MongoDB shut down on 30 September 2025.

Solution: Replace the Data API calls with the driver-based mongo-proxy Edge Function from step 3 and delete the old MONGODB_DATA_API_URL and MONGODB_API_KEY secrets.

MongoServerSelectionError or a connection timeout from the Edge Function

Cause: Atlas Network Access is blocking the Edge Function, or the connection string points at the wrong cluster.

Solution: In Atlas → Network Access, allow the Edge Function to connect (Edge Functions have no fixed IP), and re-copy the SRV string from Atlas → Connect → Drivers into MONGODB_URI.

'bad auth : authentication failed'

Cause: The user name or password in MONGODB_URI is wrong, or the password contains special characters that were not URL-encoded.

Solution: Reset the database user's password in Atlas → Database Access, URL-encode special characters, and update MONGODB_URI in Cloud → Secrets.

CORS error in the browser console when calling the function

Cause: The Edge Function does not answer the OPTIONS preflight or omits CORS headers on some responses.

Solution: Return the corsHeaders object on the OPTIONS response and on every other response, including errors, as in the step 3 template.

typescript
1if (req.method === 'OPTIONS') {
2 return new Response('ok', { headers: corsHeaders });
3}

Best practices

  • Always run MongoDB queries inside an Edge Function. Never connect to Atlas from React: the connection string would be visible to every visitor.
  • Create one MongoClient per function instance and reuse it across requests instead of connecting on every call.
  • Give the Atlas database user the narrowest role that works (for example readWrite on one database).
  • Allow-list the collections and operations the frontend may call, and validate every input before it reaches the driver.
  • Require a signed-in Supabase user for writes and store the user id on each document you create.
  • Log the collection and operation name in the Edge Function, never document contents or credentials.
  • Choose MongoDB Atlas over Lovable Cloud only when your data is genuinely document-oriented or already lives in Atlas.
  • Use limit() and pagination on every query so large collections do not time out the Edge Function.

Alternatives

Frequently asked questions

Does the MongoDB Atlas Data API still work with Lovable?

No. MongoDB ended the Atlas Data API and HTTPS Endpoints on 30 September 2025. Use the MongoDB Node.js driver inside an Edge Function instead.

Can I use MongoDB Atlas with Lovable's free plan?

Yes, with some limitations. MongoDB Atlas has a free M0 cluster tier, and Lovable's free plan supports Edge Functions. The main constraint is that the Lovable free plan limits Edge Function invocations through its Cloud usage quota. For low-traffic development and testing, the combination of Atlas M0 and Lovable free tier is completely functional. For production apps with significant traffic, you will likely need both a paid Atlas tier (for performance) and a Lovable paid plan (for usage limits).

Why use MongoDB Atlas instead of Lovable's built-in Supabase database?

Use MongoDB Atlas when your data is genuinely document-oriented — highly variable schemas where different records have completely different fields, deeply nested JSON structures, or when you already have existing data in MongoDB that you cannot migrate. Supabase PostgreSQL is the better default for most Lovable apps because it comes with AI-assisted schema management, auto-generated RLS policies, real-time subscriptions, and full AI-assisted code generation. Choosing Atlas means manually writing all Edge Function code with no AI scaffolding for database operations.

Will MongoDB Atlas queries work in Lovable's editor preview?

Yes. The browser calls your Edge Function, and the Edge Function connects to Atlas server-side with the MongoDB driver, so the connection string never reaches the browser. Preview only fails if the function has not been deployed yet or Atlas Network Access blocks it.

How do I query by _id with the MongoDB driver?

Convert the string id from the frontend to an ObjectId inside the Edge Function (new ObjectId(id)) before filtering, and return ids to the frontend as strings.

Should I use MongoDB or Lovable Cloud (Supabase) for a new Lovable app?

For a new app, Lovable Cloud is simpler: auth, database and row level security are built in (see the Lovable Supabase integration). Use MongoDB when your data already lives in Atlas or another system depends on it.

RapidDev

Talk to an Expert

Our team has built 1,000+ apps. Get personalized help with your project.

Book a free consultation
Matt Graham

Written by

Matt Graham · CEO & Founder, RapidDev

1,000+ client projects delivered. Columbia University & Harvard Business School alumnus, U.S. Navy veteran. About the author →

Integrations are where projects stall

We wire Lovable integrations like this one every week — auth, webhooks, edge cases included. Fixed-price builds from $13K, delivered in 6–10 weeks.

Talk to an integration engineer

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.