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
- Frontend: Vite (hosted on Vercel)
- Backend: AWS Lambda (Node.js)
- Database: MongoDB Atlas
- Deployment: Lambda Function URL
Step 1: Create Your MongoDB Atlas Cluster
First things first, set up your MongoDB cluster on MongoDB Atlas:
- Create a free cluster.
- Create a database and a subscribers collection.
- Whitelist your IP or allow access from anywhere (for testing).
- Grab the connection string (with your username and password embedded).
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 }), }; } };
๐ 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
Zip it:
cd .. zip -r mongodb-layer.zip nodejs
Upload it to AWS Lambda > Layers, and attach it to your function.
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!
- Go to your Lambda function
- Click on "Function URL"
- Enable it and choose โAuth: NONEโ (or configure custom auth if needed)
- 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: "test@example.com" }), }) .then(res => res.json()) .then(data => console.log(data.message));
Boom! ๐ Now you're collecting emails without maintaining any servers.
๐ค Why Not Use API Gateway or a Framework?
Great question. I wanted to:
- Avoid API Gateway setup (extra steps, more config)
- Keep it ultra lightweight for MVP
- 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)