Developing Web Applications with Netlify Serverless Functions with MongoDB Atlas
Jayaprakash A V, CSM?
Senior Consultant | SAP S/4HANA MM | AI / ML / Big Data Specialist | Expert Technical Lead | Certified ScrumMaster? | MTech (CS) in ML & Big Data | Masters in Computer Applications | Master of Business Administration
Serverless computing has gained significant popularity in recent years due to its scalability, flexibility, and cost-effectiveness. One of the leading platforms enabling developers to create serverless applications seamlessly is Netlify. This article delves into how to develop a web application using Netlify serverless functions with a practical example of fetching movie data from MongoDB's sample_mflix dataset.
What Are Netlify Serverless Functions?
Netlify serverless functions allow you to execute backend code without managing a dedicated server. They run in response to HTTP requests and are powered by AWS Lambda. You can use serverless functions to handle tasks like API requests, form submissions, authentication, and data fetching.
Prerequisites
To follow along, ensure you have:
Setting Up the Project
Set Up Netlify CLI: Install Netlify CLI globally if not already installed:
npm install -g netlify-cli
Login to your Netlify account:
netlify sites:create
Site name (leave blank for a random name; you can change it later): netlify-example-web-app
Install Dependencies: Install the required packages for MongoDB and environment variable management:
Install mongoDB
npm install mongodb
Optional dependency:
npm install dotenv
Advantages of using serverless functions along with a database (Ex: MongoDB)
Using serverless functions in conjunction with a database like MongoDB offers several advantages, enabling developers to build scalable, efficient, and cost-effective applications. Here are the key benefits:
1. Scalability
2. Cost Efficiency
3. Simplified Development
4. Global Accessibility
5. Security
6. Flexibility
7. Event-Driven Workflows
8. Cross-Platform Integration
Load the sample data on MongoDB cluster before starting the database integration process.
MongoDB Atlas sample_mflix.movies collection screen.
Get started with Netlify CLI
Netlify’s command line interface (CLI) lets you configure continuous deployment straight from the command line. You can use Netlify CLI to run a local development server that you can share with others, run a local build and plugins, and deploy your site.
The command netlify functions:create --name get_movies is used to create a new serverless function named get_movies in a Netlify project. Here's what it does:
Netlify dashboard:
Create an .env File: Add MongoDB configuration variables on it:
MONGODB_URI=mongodb+srv://<user_name>:<password>@mdbcluster.5hhuz.mongodb.net/?retryWrites=true&w=majority
MONGODB_DATABASE=sample_mflix
MONGODB_COLLECTION=movies
Secure Environment Variables: Ensure the .env file is added to .gitignore:
We can configure Netlify environment variables for the project either through the Netlify CLI or via the Netlify dashboard.
netlify env:set MONGODB_URI "mongodb+srv://<user_name>:<password>@mdbcluster.5hhuz.mongodb.net/?retryWrites=true&w=majority"
netlify env:set MONGODB_DATABASE sample_mflix
netlify env:set MONGODB_COLLECTION movies
Update codebase on the get_movies.js file (Located at functions/get_movies)
const { MongoClient } = require("mongodb")
require('dotenv').config()
const mongoClient = new MongoClient(process.env.MONGODB_URI);
const clientPromise = mongoClient.connect();
const handler = async (event, context) => {
try {
const database = (await clientPromise).db(process.env.MONGODB_DATABASE);
const collection = database.collection(process.env.MONGODB_COLLECTION);
const results = await collection.find({}).limit(5).toArray();
return {
statusCode: 200,
body: JSON.stringify(results),
};
} catch (error) {
return { statusCode: 500, body: error.toString() };
}
};
module.exports = { handler };
Create a files, inex.html on the root directory for displaying the movies.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Netlify Web Application Deployment</title>
</head>
<body>
<h2>Netlify Web Application Deployment</h2>
<ul id="movies">
</ul>
<script>
(async ()=> {
try {
let results = await fetch('/.netlify/functions/get_movies').then(res => res.json());
results.forEach(result => {
const listItem = document.createElement('li');
listItem.innerText = result.title;
document.getElementById('movies').appendChild(listItem);
});
} catch (e) {
console.error(e);
}
})();
</script>
</body>
</html>
For testing the app, run
netlify dev
It runs the netlify application on the local environment. We can access it on : https://localhost:8888/
Deploying the application to the Netlify platform.
Run the command on CLI:
netlify deploy
Follow the prompts to configure your site.
Access the draft URL:
By leveraging Netlify serverless functions, you can quickly build scalable web applications without managing server infrastructure. This example showcases how to use JavaScript, Netlify, and MongoDB to fetch and display data dynamically. With these tools, you can create robust applications that are efficient, easy to maintain, and deploy.
#NetlifyFunctions
#ServerlessComputing
#WebDevelopment
#MongoDB
#JavaScript
#ServerlessApps
#CloudDevelopment
#FullStackDev
#APIDevelopment
#BackendDevelopment
#NetlifyDev
#WebApps
#MongoDBAtlas
#WebDevelopmentTips
#FrontendBackend
#DatabaseIntegration
#CodingLife
#DeveloperTools
#ModernWebDev
#BuildAndDeploy
#ScalableApps
#ProgrammingTips
#Programming
#Coding
#SoftwareDevelopment
#TechCommunity
#WebDevelopment
#CodeNewbie
#FullStackDeveloper
#DeveloperLife
#CodeChallenges
#OpenSource
#TechInnovation
#DataScience
#MachineLearning
#AIProgramming
#CloudComputing
#DevOps
#LearnToCode
#CodingLife
#TechCareers
#ProgrammingLife
#WomenInTech
#JavaScriptDeveloper
#PythonDeveloper
#CodeWithMe
#TechSkills
Jayaprakash A V, CSM?, combining netlify's serverless capabilities with mongodb atlas creates powerful, scalable solutions. have you explored their latest integrations? ?? #clouddev