Tutorials

Deploying a Full-Stack JAMstack App with DigitalOcean and Netlify

[]Introduction

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:

  • Log in to your DigitalOcean account.
  • Navigate to Databases → Create Database Cluster.
  • Select MongoDB as the database engine.
  • Once created, copy the connection string by going to Overview → Connection Details(with credentials included) and store it to a notepad file locally(You will need it later in the tutorial while adding DigitalOcean as a Netlify extension).

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

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:

my-jamstack-app/src/Api.js

import { useState, useEffect } from “react”; function App() { const [items, setItems] = useState([]); const [newItem, setNewItem] = useState(“”); useEffect(() => { fetch(“/.netlify/functions/connectMongo”) .then((res) => res.json()) .then((data) => setItems(data)); }, []); const addItem = () => { fetch(“/.netlify/functions/connectMongo”, { method: “POST”, headers: { “Content-Type”: “application/json” }, body: JSON.stringify({ name: newItem }) }).then(() => { window.location.reload(); }); }; return (

MongoDB Items

    {items.map((item) => (

  • {item.name}
  • ))}

setNewItem(e.target.value)} />

); } export default App; []Build the API with Netlify Serverless Functions

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.

my-jamstack-app/functions/connectMongo.js

const { MongoClient } = require(“mongodb”); exports.handler = async function (event) { const client = new MongoClient(process.env.MONGODB_URL); try { await client.connect(); const db = client.db(“mydatabase”); const collection = db.collection(“items”); if (event.httpMethod === “GET”) { const data = await collection.find({}).toArray(); return { statusCode: 200, body: JSON.stringify(data) }; } if (event.httpMethod === “POST”) { const newItem = JSON.parse(event.body); await collection.insertOne(newItem); return { statusCode: 201, body: JSON.stringify({ message: “Item added successfully” }) }; } return { statusCode: 405, body: JSON.stringify({ error: “Method Not Allowed” }) }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: error.message }) }; } finally { await client.close(); } }; []Create a Git Repository and Push Code to GitHub

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 []Manually Build & Deploy from cmdline

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.

Output

This 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:

[]Add the DigitalOcean Extension

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button