FRESH DEALS: KVM VPS PROMOS NOW AVAILABLE IN SELECT LOCATIONS!

DediRock is Waging War On High Prices Sign Up Now

Step-by-Step Guide to Deploying a Full-Stack JAMstack App with DigitalOcean and Netlify

Deploying a Full-Stack JAMstack App with DigitalOcean and Netlify

Introduction

JAMstack (JavaScript, APIs, Markup) is a modern web architecture that emphasizes speed, security, and easy maintenance. It is suitable for developers looking to build fast, dynamic applications for various use cases, such as e-commerce, blogs, and single-page apps. This tutorial will guide you through deploying a full-stack JAMstack application utilizing:

  • Netlify for hosting.
  • DigitalOcean Managed MongoDB for the database.
  • DigitalOcean Netlify Extension to manage database connections effortlessly.

By the end of this tutorial, you will have a fully operational JAMstack app deployed on Netlify, connected to a MongoDB database hosted on DigitalOcean.

Prerequisites

Before you start, make sure you have:

  • A DigitalOcean account to set up a Managed MongoDB database.
  • A Netlify account.
  • Node.js and npm installed locally.
  • Git installed locally.
  • Basic understanding of JavaScript and React.

Step 1 – Set Up DigitalOcean Managed MongoDB

First, create a Managed MongoDB cluster on DigitalOcean:

  1. Log into your DigitalOcean account.
  2. Navigate to Databases → Create Database Cluster.
  3. Select MongoDB as the database engine.
  4. After creation, copy the connection string found under Overview → Connection Details. Keep it in a safe place as you’ll need it later.

Step 2 – Enable Netlify Extension for DigitalOcean MongoDB

To connect your Netlify account with DigitalOcean, you’ll need to install the DigitalOcean Netlify extension:

  1. Log into your Netlify account.
  2. Go to the Extensions tab in the sidebar.
  3. Search for DigitalOcean.
  4. Click Install, then add it to your Netlify Site.

Step 3 – Create a Full-Stack JAMstack App

Now, create your JAMstack App using React and a Vite template:

In your terminal:

npx create-vite my-jamstack-app --template reactcd my-jamstack-appnpm installnpm install mongodb

Create a file Api.js in the src directory to fetch data from the serverless function:

import { useState, useEffect } from "react";// Function to handle the state of items and new item inputfunction App() {  const [items, setItems] = useState([]);  const [newItem, setNewItem] = useState("");  // Fetch items from MongoDB on component mount  useEffect(() => {    fetch("/.netlify/functions/connectMongo")      .then((res) => res.json())      .then((data) => setItems(data));  }, []);  // Function to add a new item to MongoDB  const addItem = () => {    fetch("/.netlify/functions/connectMongo", {      method: "POST",      headers: {        "Content-Type": "application/json",      },      body: JSON.stringify({ name: newItem }),    }).then(() => {      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;

Step 4 – Build the API with Netlify Serverless Functions

Create a functions directory in your project to implement the backend logic, specifically a file named 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");    // Handling GET requests    if (event.httpMethod === "GET") {      const data = await collection.find({}).toArray();      return {        statusCode: 200,        body: JSON.stringify(data),      };    }    // Handling POST requests    if (event.httpMethod === "POST") {      const newItem = JSON.parse(event.body);      await collection.insertOne(newItem);      return {        statusCode: 201,        body: JSON.stringify({ message: "Item added successfully" }),      };    }    // Handle other HTTP methods    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();  }};

Step 5 – Create a Git Repository and Push Code to GitHub

Initialize a Git repository:

git initgit add .git commit -m "Initial commit"

Create a new repository on GitHub, then add it as a remote origin:

git remote add origin https://github.com/your-username/your-repo.gitgit push -u origin main

Step 6 – Build and Deploy Backend with Netlify Functions

Install the Netlify CLI:

npm install -g netlify-cli

To manually deploy from the command line:

netlify deploy

Follow the prompts to create a new site and specify your publish directory as /my-jamstack-app.

Step 7 – Add the DigitalOcean Extension

Return to the Extensions section in Netlify and input the previously saved MongoDB connection string. This will allow your functions access to the database.

Testing and Conclusion

You can verify that your app works correctly by sending a POST request to add data and a GET request to retrieve it using cURL commands. Check the responses to ensure database operations are successful.

Congratulations! You have created a full-stack JAMstack application using DigitalOcean’s database solutions and Netlify. You can now explore different ways to expand your app’s functionalities.


Welcome to DediRock, your trusted partner in high-performance hosting solutions. At DediRock, we specialize in providing dedicated servers, VPS hosting, and cloud services tailored to meet the unique needs of businesses and individuals alike. Our mission is to deliver reliable, scalable, and secure hosting solutions that empower our clients to achieve their digital goals. With a commitment to exceptional customer support, cutting-edge technology, and robust infrastructure, DediRock stands out as a leader in the hosting industry. Join us and experience the difference that dedicated service and unwavering reliability can make for your online presence. Launch our website.

Share this Post

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Search

Categories

Tags

0
Would love your thoughts, please comment.x
()
x