Sr Technical Writer
JAMstack (JavaScript, APIs, and Markup) is a modern architecture for building fast and scalable web applications. It offers numerous benefits, including improved performance, enhanced security, and simplified maintenance.
This architecture is best suited for developers and organizations seeking to create dynamic, data-driven applications with a focus on user experience. Some common use cases for JAMstack include e-commerce platforms, blogs, and single-page applications.
In this tutorial, you’ll learn how to deploy a full-stack JAMstack application using:
By the end of this guide, you’ll have a working JAMstack app deployed on Netlify with a connected MongoDB database on DigitalOcean and by using the Netlify Extensions.
Before you begin, ensure you have:
First, you will create a Managed MongoDB cluster deployed on DigitalOcean. You can easily create production-ready MongoDB databases on DigitalOcean. For a step-by-step guide, watch this video:
Steps to create a Managed MongoDB cluster on DigitalOcean
You can also refer to this tutorial on How to Manage Data with MongoDB.
The steps are simple:
In this step you will install the DigitalOcean Netlify extension. You will use this extension to connect to your DigitalOcean account and start deploying and connecting cloud resources to your Netlify sites.
You need to login to your Netlify account. Sign up and go to Extensions tab from the sidebar.
Let’s start creating a full-stack JAMstack App.
You will use a React and Vite frontend template to interact with MongoDB.
Go to your terminal and use the below commands to setup an application template:
npx create-vite my-jamstack-app --template react
cd my-jamstack-app
npm install
npm install mongodb
Note: If you don’t have Node.js and npm
installed, then you can refer the documentation on Installing Node.js and npm.
The above command should setup a basic application template.
Now go inside src
directory, create a file Api.js
to fetch data from the serverless function:
import { useState, useEffect } from "react";
// Function to handle the state of items and new item input
function App() {
// Initialize state for items and new item input
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState("");
// UseEffect hook to fetch items from MongoDB on component mount
useEffect(() => {
// Fetch data from the serverless function
fetch("/.netlify/functions/connectMongo")
.then((res) => res.json())
.then((data) => setItems(data));
}, []);
// Function to add a new item to MongoDB
const addItem = () => {
// POST request to the serverless function to add a new item
fetch("/.netlify/functions/connectMongo", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newItem })
}).then(() => {
// Reload the window to reflect the changes
window.location.reload();
});
};
// JSX to render the items list, input for new item, and an add button
return (
<div>
<h1>MongoDB Items</h1>
<ul>{items.map((item) => (<li key={item._id}>{item.name}</li>))}</ul>
<input value={newItem} onChange={(e) => setNewItem(e.target.value)} />
<button onClick={addItem}>Add Item</button>
</div>
);
}
export default App;
Let’s create a functions
directory inside the root directory of this project. You can read more about Netlify Functions.
mkdir functions
cd functions/
Next, inside the functions
directory let’s create a file connectMongo.js
.
// Importing the MongoClient class from the mongodb package
const { MongoClient } = require("mongodb");
// Defining the serverless function
exports.handler = async function (event) {
// Creating a new MongoClient instance with the MongoDB URL from the environment variables
const client = new MongoClient(process.env.MONGODB_URL);
try {
// Connecting to the MongoDB server
await client.connect();
// Accessing the "mydatabase" database
const db = client.db("mydatabase");
// Accessing the "items" collection
const collection = db.collection("items");
// Handling GET requests
if (event.httpMethod === "GET") {
// Fetching all items from the collection and converting the result to an array
const data = await collection.find({}).toArray();
// Returning a 200 status code and the fetched data
return {
statusCode: 200,
body: JSON.stringify(data)
};
}
// Handling POST requests
if (event.httpMethod === "POST") {
// Parsing the request body to get the new item
const newItem = JSON.parse(event.body);
// Inserting the new item into the collection
await collection.insertOne(newItem);
// Returning a 201 status code and a success message
return {
statusCode: 201,
body: JSON.stringify({ message: "Item added successfully" })
};
}
// Handling other HTTP methods
return {
statusCode: 405,
body: JSON.stringify({ error: "Method Not Allowed" })
};
} catch (error) {
// Handling any errors that occur during the execution of the function
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
} finally {
// Closing the MongoDB client connection
await client.close();
}
};
Initialize a Git repository in your project directory i.e., inside my-jamstack-app
:
git init
Add all project files to Git:
git add .
Commit the changes:
git commit -m "Initial commit"
Now, go to your GitHub account and create a new repository.
Next, add the remote origin:
git remote add origin https://github.com/your-username/your-repo.git
Push your code to GitHub:
git push -u origin main
You will use the Netlify ClI to create a new “Site” and do a mannual deploy from command line.
Using Netlify CLI 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.
Let’s install the Netlify CLI:
npm install -g netlify-cli
Use the following command to deploy the site manually from command line.
netlify deploy
Follow the on-sreen instructions to create a new site and other settings.
OutputThis folder isn't linked to a site yet
? What would you like to do? + Create & configure a new site
? Team: asinghwalia’s team
? Site name (leave blank for a random name; you can change it later): netlify-digitalocean-app
Site Created
Admin URL: https://app.netlify.com/sites/netlify-digitalocean-app
URL: https://netlify-digitalocean-app.netlify.app
Site ID: 985f40e7-8892-4b9d-9e36-5ea74c494874
Adding local .netlify folder to .gitignore file...
Linked to netlify-digitalocean-app
Please provide a publish directory (e.g. "public" or "dist" or "."):
? Publish directory /my-jamstack-app
Deploy path: /my-jamstack-app
Deploying to draft URL...
⠋ Uploading blobs to deploy store...
Netlify Build
────────────────────────────────────────────────────────────────
❯ Version
@netlify/build 29.58.8
❯ Flags
deployId: 679dc88c9705fce5ffd42051
open: false
prod: false
prodIfUnlocked: false
skipFunctionsCache: false
❯ Current directory
/my-jamstack-app
❯ Config file
No config file was defined: using default values.
❯ Context
✔ Finished uploading blobs to deploy store
✔ No cached functions were found
✔ Finished hashing
✔ CDN requesting 4 files
✔ Finished uploading 4 assets
✔ Deploy is live!
Build logs: https://app.netlify.com/sites/netlify-digitalocean-app/deploys/679dc88c9705fce5ffd42051
Function logs: https://app.netlify.com/sites/netlify-digitalocean-app/logs/functions?scope=deploy:679dc88c9705fce5ffd42051
Edge function Logs: https://app.netlify.com/sites/netlify-digitalocean-app/logs/edge-functions?scope=deployid:679dc88c9705fce5ffd42051
Website draft URL: https://679dc88c9705fce5ffd42051--netlify-digitalocean-app.netlify.app
If everything looks good on your draft URL, deploy it to your main site URL with the --prod flag.
netlify deploy --prod
Now if you go to Netlify Sites, you should see a new Site created.
Now you will need to link the Git repository, created in the last step.
Go to Site Configuration from the left side panel and click “Build & deploy” and “Link repository”.
Select “Github” and add your repository and configure the build settings.
Now, select your Github repository:
Now configure and add build settings and then deploy the site.
Note: Make sure to set the “Functions Directory” to “/functions” which we created in this tutorial. You can leave the remaining build settings as default.
You can go to “Site Overview” to check the deployment status:
Now head over to “Extensions” and add the MongoDB connection String saved earlier in this tutorial.
The connection string will now be available in your Netlify project’s environment variables. It can now be accessed by your Netlify Functions.
You can also go to “Site Configuration” -> “Environment variables” and check the automatically added MongoDB environment variable by using the DigitalOcean extension.
Now let’s check the netlify function endpoint and perform some database operations.
You can find the function endpoint by going to Sites -> Logs -> Functions.
Use the below curl
command to store some data to the MongoDB database.
curl -X POST https://netlify-digitalocean-app.netlify.app/.netlify/functions/connectMongo \
-H "Content-Type: application/json" \
-d '{"Item 1": "New Item 1"}'
You should see the following output:
Output{"message":"Item added successfully"}
Let’s execute a GET
request to retrive the data:
curl -X GET https://netlify-digitalocean-app.netlify.app/.netlify/functions/connectMongo
Output[{"_id":"679dcdd3d9dc4d82c9de1ddd","name":"New Item"},{"_id":"679dcdebd9dc4d82c9de1dde","Item 2":"New Item 2"},{"_id":"679dd3ab2849e603f9d5813b","Item 3":"New Item 3"}]%
You can also verify the POST
operation’s success by going to the function endpoint in your browser.
DigitalOcean’s Managed MongoDB provides several features that make it a powerful and convenient choice for developers:
To install the DigitalOcean Netlify Extension:
This integration simplifies the deployment and database management process for developers:
No, DigitalOcean provides a range of managed databases, including:
Security is a key focus of this integration, and it is handled through multiple layers:
Congratulations! You have successfully deployed a full-stack JAMstack application using DigitalOcean MongoDB and Netlify. Your application now features a practical React frontend that interacts with MongoDB.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!