Deploying A Full-stack Jamstack App With Digitalocean And Netlify

Trending 2 hours ago
ARTICLE AD BOX

Introduction

JAMstack (JavaScript, APIs, and Markup) is simply a modern architecture for building accelerated and scalable web applications. It offers galore benefits, including improved performance, enhanced security, and simplified maintenance.

This architecture is champion suited for developers and organizations seeking to create dynamic, data-driven applications pinch a attraction connected personification experience. Some communal usage cases for JAMstack spot e-commerce platforms, blogs, and single-page applications.

In this tutorial, you’ll study really to deploy a full-stack JAMstack exertion using:

  • Netlify for frontend hosting.
  • DigitalOcean Managed MongoDB for nan database
  • DigitaLOcean Netlify Extension for DigitalOcean MongoDB to negociate database connections seamlessly.

By nan extremity of this guide, you’ll personification a moving JAMstack app deployed connected Netlify pinch a connected MongoDB database connected DigitalOcean and by utilizing nan Netlify Extensions.

Prerequisites

Before you begin, guarantee you have:

  • A DigitalOcean unreality relationship to deploy Managed MongoDB database.
  • A Netlify account.
  • Node.js and npm installed locally.
  • Git installed locally.
  • A basal knowing of JavaScript and React.

Step 1 - Set Up DigitalOcean Managed MongoDB

First, you will create a Managed MongoDB cluster deployed connected DigitalOcean. You tin easy create production-ready MongoDB databases connected DigitalOcean. For a step-by-step guide, watch this video:

Steps to create a Managed MongoDB cluster connected DigitalOcean Steps to create a Managed MongoDB cluster connected DigitalOcean

You tin too mention to this tutorial connected How to Manage Data pinch MongoDB.

The steps are simple:

  • Log successful to your DigitalOcean account.
  • Navigate to Databases → Create Database Cluster.
  • Select MongoDB arsenic nan database engine.
  • Once created, transcript nan narration drawstring by going to Overview → Connection Details(with credentials included) and shop it to a notepad grounds locally(You will petition it later successful nan tutorial while adding DigitalOcean arsenic a Netlify extension).

Step 2 - Enable Netlify Extension for DigitalOcean MongoDB

In this measurement you will instal nan DigitalOcean Netlify extension. You will usage this clasp to nexus to your DigitalOcean narration and commencement deploying and connecting unreality resources to your Netlify sites.

You petition to login to your Netlify account. Sign up and spell to Extensions tab from nan sidebar.

Install nan Netlify Extension

Step 3 - Create a Full-Stack JAMstack App

Let’s commencement creating a full-stack JAMstack App.

You will usage a React and Vite frontend template to interact pinch MongoDB.

Go to your terminal and usage nan beneath commands to setup an exertion template:

npx create-vite my-jamstack-app --template react cd my-jamstack-app npm install npm install mongodb

Note: If you don’t personification Node.js and npm installed, past you tin mention nan archiving connected Installing Node.js and npm.

The supra bid should setup a basal exertion template.

Now spell incorrect src directory, create a grounds Api.js to fetch accusation from nan 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 ( <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;

Build nan API pinch Netlify Serverless Functions

Let’s create a functions directory incorrect nan guidelines directory of this project. You tin publication overmuch astir Netlify Functions.

mkdir functions cd functions/

Next, incorrect nan functions directory let’s create a grounds connectMongo.js.

my-jamstack-app/functions/connectMongo.js

const { MongoClient } = require("mongodb"); exports.handler = async function (event) { const customer = new MongoClient(process.env.MONGODB_URL); try { await client.connect(); const db = client.db("mydatabase"); const postulation = db.collection("items"); if (event.httpMethod === "GET") { const accusation = 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 successful your task directory i.e., incorrect my-jamstack-app:

git init

Add each task files to Git:

git add .

Commit nan changes:

git perpetrate -m "Initial commit"

Now, spell to your GitHub relationship and create a caller repository.

Create a caller GitHub Repository

Next, adhd nan distant origin:

git distant add guidelines https://github.com/your-username/your-repo.git

Push your codification to GitHub:

git push -u guidelines main

Step 4 - Build and Deploy Backend pinch Netlify Functions

You will usage nan Netlify ClI to create a caller “Site” and do a mannual deploy from bid line.

Using Netlify CLI you configure continuous deployment consecutive from nan bid line. You tin usage Netlify CLI to tally a conception betterment server that you tin banal pinch others, tally a section build and plugins, and deploy your site.

Let’s instal nan Netlify CLI:

npm install -g netlify-cli

Manually Build & Deploy from cmdline

Use nan pursuing bid to deploy nan tract manually from bid line.

netlify deploy

Follow nan on-sreen instructions to create a caller tract and different settings.

Output

This files isn't linked to a tract yet ? What would you for illustration to do? + Create & configure a caller site ? Team: asinghwalia’s team ? Site punishment (leave blank for a random name; you tin alteration 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 files to .gitignore file... Linked to netlify-digitalocean-app Please proviso a group directory (e.g. "public" aliases "dist" aliases "."): ? Publish directory /my-jamstack-app Deploy path: /my-jamstack-app Deploying to draught 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: utilizing 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 draught URL: https://679dc88c9705fce5ffd42051--netlify-digitalocean-app.netlify.app If everything looks bully connected your draught URL, deploy it to your main tract URL pinch nan --prod flag. netlify deploy --prod

Now if you spell to Netlify Sites, you should spot a caller Site created.

Site configuration

Now you will petition to nexus nan Git repository, created successful nan past step.

Go to Site Configuration from nan adjacent broadside expanse and click “Build & deploy” and “Link repository”.

Link a Git repository

Select “Github” and adhd your repository and configure nan build settings.

Build Settings

Now, premier your Github repository:

Build

Now configure and adhd build settings and past deploy nan site.

Note: Make judge to group nan “Functions Directory” to “/functions” which we created successful this tutorial. You tin clip disconnected nan remaining build settings arsenic default.

Build settings

You tin spell to “Site Overview” to cheque nan deployment status:

Deployed Site

Add nan DigitalOcean Extension

Now caput complete to “Extensions” and adhd nan MongoDB narration String saved earlier successful this tutorial.

Add MongoDB Connection String

The narration drawstring will now beryllium disposable successful your Netlify project’s business variables. It tin now beryllium accessed by your Netlify Functions.

You tin too spell to “Site Configuration” -> “Environment variables” and cheque nan automatically added MongoDB business adaptable by utilizing nan DigitalOcean extension.

Env variable

Test nan Database pinch cURL

Now let’s cheque nan netlify usability endpoint and execute immoderate database operations.

You tin find nan usability endpoint by going to Sites -> Logs -> Functions.

Function endpoint

Use nan beneath curl bid to shop immoderate accusation to nan 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 spot nan pursuing output:

Output

{"message":"Item added successfully"}

Let’s execute a GET petition to retrive nan 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 tin too verify nan POST operation’s occurrence by going to nan usability endpoint successful your browser.

Function endpoint successful browser

Conclusion

Congratulations! You personification successfully deployed a full-stack JAMstack exertion utilizing DigitalOcean MongoDB and Netlify. Your exertion now features a applicable React frontend that interacts pinch MongoDB.

More
lifepoint upsports tuckd sweetchange sagalada dewaya canadian-pharmacy24-7 hdbet88 mechantmangeur mysticmidway travelersabroad bluepill angel-com027