DEV Community

Raj Shah
Raj Shah

Posted on

Serverless MongoDB Integration on AWS: A No-Bloat Lambda Approach

Hey everyone! đź‘‹

I recently started building futurejobs.today — a job board platform that helps people find future-focused jobs in tech. While the main site is under development, I wanted to quickly set up a Coming Soon page to collect emails of people who are interested.

Sounds simple, right? But there was a catch — I wanted to do it serverless, use MongoDB as my backend, and not bloat my Lambda function with extra MBs of dependencies. While MongoDB’s docs touch on this, they didn’t go deep enough. So here’s how I actually made it work — and I hope this blog helps someone avoid the detours I had to take.

đź§© The Stack

  1. Frontend: Vite (hosted on Vercel)
  2. Backend: AWS Lambda (Node.js)
  3. Database: MongoDB Atlas
  4. Deployment: Lambda Function URL

Step 1: Create Your MongoDB Atlas Cluster

First things first, set up your MongoDB cluster on MongoDB Atlas:

  1. Create a free cluster.
  2. Create a database and a subscribers collection.
  3. Whitelist your IP or allow access from anywhere (for testing).
  4. Grab the connection string (with your username and password embedded).

MongoDB Network Access Config

Step 2: Write the Lambda Function

Here's a basic Lambda handler in Node.js that connects to MongoDB and saves an email:

const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGODB_URI);

exports.handler = async function (event) {
  const headers = {
    'Content-Type': 'application/json'
  };

  // Handle preflight OPTIONS request
  if (event.requestContext?.http?.method === 'OPTIONS') {
    return {
      statusCode: 200,
      headers,
      body: '',
    };
  }

  try {
    const email = event.queryStringParameters?.email || JSON.parse(event.body || '{}').email;

    if (!email) {
      return {
        statusCode: 400,
        headers,
        body: JSON.stringify({ error: 'Email is required' }),
      };
    }

    await client.connect();
    const db = client.db('emails');
    const collection = db.collection('emails');

    // Check if email already exists
    const existing = await collection.findOne({ email: email.toLowerCase() });

    if (existing) {
      return {
        statusCode: 200,
        headers,
        body: JSON.stringify({ message: 'Email already signed up' }),
      };
    }

    // Insert new email
    const result = await collection.insertOne({ email: email.toLowerCase(), createdAt: new Date() });

    return {
      statusCode: 200,
      headers,
      body: JSON.stringify({
        message: 'Email added successfully',
        insertedId: result.insertedId,
      }),
    };
  } catch (err) {
    console.error('Error inserting email:', err);
    return {
      statusCode: 500,
      headers,
      body: JSON.stringify({ error: err.message }),
    };
  }
};

Enter fullscreen mode Exit fullscreen mode

📝 Note: Don’t forget to set the MONGO_URI environment variable in your Lambda function config.

Step 3: Add MongoDB Node.js Driver via Lambda Layer

Here’s where things get a bit tricky.

Lambda has a 50MB limit for deployment packages, and the MongoDB Node.js driver is… kinda chunky. To keep things clean, we’ll use a Lambda Layer.

On your local machine, run:

mkdir -p layer/nodejs
cd layer/nodejs
npm init -y
npm install mongodb
Enter fullscreen mode Exit fullscreen mode

Zip it:

cd ..
zip -r mongodb-layer.zip nodejs
Enter fullscreen mode Exit fullscreen mode

Upload it to AWS Lambda > Layers, and attach it to your function.

Add a Lambda Layer

In your Lambda, just make sure to require('mongodb') — AWS will automatically resolve it from the Layer.

Step 4: Expose the Function Using Lambda Function URL

You don’t have to set up API Gateway just to get a POST endpoint. Lambda Function URLs to the rescue!

  1. Go to your Lambda function
  2. Click on "Function URL"
  3. Enable it and choose “Auth: NONE” (or configure custom auth if needed)
  4. Copy the URL — that’s your API endpoint!

Step 5: Test It

Now you can make a simple POST request from your frontend:

fetch("https://your-lambda-url.amazonaws.com", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email: "[email protected]" }),
})
.then(res => res.json())
.then(data => console.log(data.message));

Enter fullscreen mode Exit fullscreen mode

Boom! 🎉 Now you're collecting emails without maintaining any servers.

🤔 Why Not Use API Gateway or a Framework?

Great question. I wanted to:

  1. Avoid API Gateway setup (extra steps, more config)
  2. Keep it ultra lightweight for MVP
  3. Get to market fast

This setup does exactly that. Fast, serverless, and minimal dependencies.

📝 Final Thoughts

Even though MongoDB's docs mention Lambda support, there’s a surprising lack of complete real-world examples — especially when combining Lambda Layers, Function URLs, and MongoDB.

If you're building a similar setup, I hope this post saves you a few hours of debugging 🙌

Thanks for reading! Follow me here on dev.to or check out futurejobs.today to see the full platform once it’s live 🚀

Top comments (0)