Developing Web App using React Cosmos DB - Connect to CosmosDB - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Thursday, July 9, 2026

Developing Web App using React Cosmos DB - Connect to CosmosDB

Developing Web App using React Cosmos DB - Connect to CosmosDB

Screenshot from the tutorial
Screenshot from the tutorial

Developing a Web App using React and Cosmos DB: A Step-by-Step Guide

In today’s digital landscape, building robust web applications requires a combination of powerful frontend frameworks and scalable backend databases. This blog post will guide you through developing a web application using React as the frontend framework and Azure Cosmos DB as the backend database. We will focus on how to connect your React app to Cosmos DB, following the insights from the YouTube video titled "Developing Web App using React Cosmos DB - Connect to CosmosDB."

What is React?

React is a popular JavaScript library for building user interfaces, especially for single-page applications. It allows developers to create reusable UI components, making the development process more efficient and organized.

What is Azure Cosmos DB?

Azure Cosmos DB is a globally distributed, multi-model database service designed for high availability and low latency. It supports multiple data models, including document, key-value, graph, and column-family data, making it a versatile choice for modern applications.

Prerequisites

Before we start, ensure you have the following:

  1. Node.js and npm installed on your machine.
  2. An Azure account to create and manage your Cosmos DB instance.
  3. Basic understanding of React and JavaScript.

Step 1: Setting Up Your Cosmos DB

  1. Log in to your Azure account and navigate to the Azure portal.
  2. Click on Create a Resource and select Databases > Azure Cosmos DB.
  3. Choose the API you wish to use (for this tutorial, we will use the SQL API).
  4. Fill in the required fields like Subscription, Resource Group, Account Name, and Location.
  5. Click Review + Create and then Create to set up your Cosmos DB instance.
  6. Once created, navigate to the Keys section in your Cosmos DB account to retrieve your URI and Primary Key. You will need these to connect your React app to Cosmos DB.

Step 2: Setting Up Your React Application

  1. Open a terminal and create a new React application using Create React App:

    npx create-react-app my-cosmos-app
    
  2. Navigate to your new app directory:

    cd my-cosmos-app
    
  3. Install the necessary packages for making HTTP requests. We will use Axios for this purpose:

    npm install axios
    

Step 3: Building the Connection to Cosmos DB

We will create a simple backend using Express.js to securely connect to Cosmos DB. This backend will handle requests from our React frontend.

  1. Create a new directory for your server and navigate into it:

    mkdir server
    cd server
    
  2. Initialize a new Node.js project:

    npm init -y
    
  3. Install the required dependencies:

    npm install express @azure/cosmos dotenv cors
    
  4. Create a .env file in the server directory to store your Cosmos DB credentials:

    COSMOS_URI=your_cosmos_db_uri
    COSMOS_KEY=your_cosmos_db_primary_key
    
  5. Create a server file (e.g., server.js) and set up the Express server:

    const express = require('express');
    const { CosmosClient } = require('@azure/cosmos');
    const cors = require('cors');
    require('dotenv').config();
    
    const app = express();
    app.use(cors());
    app.use(express.json());
    
    const client = new CosmosClient({
        endpoint: process.env.COSMOS_URI,
        key: process.env.COSMOS_KEY
    });
    
    const databaseId = 'YourDatabaseId';
    const containerId = 'YourContainerId';
    
    app.get('/api/items', async (req, res) => {
        const querySpec = {
            query: 'SELECT * from c'
        };
        const { resources: items } = await client.database(databaseId).container(containerId).items.query(querySpec).fetchAll();
        res.status(200).send(items);
    });
    
    const PORT = process.env.PORT || 5000;
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    
  6. Start your server:

    node server.js
    

Step 4: Connecting React App to the Backend

Now, we will modify our React app to fetch data from the backend we just created.

  1. Open src/App.js in your React application and modify it as follows:

    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    
    const App = () => {
        const [items, setItems] = useState([]);
    
        useEffect(() => {
            const fetchItems = async () => {
                const response = await axios.get('http://localhost:5000/api/items');
                setItems(response.data);
            };
    
            fetchItems();
        }, []);
    
        return (
            <div>
                <h1>Items from Cosmos DB</h1>
                <ul>
                    {items.map(item => (
                        <li key={item.id}>{JSON.stringify(item)}</li>
                    ))}
                </ul>
            </div>
        );
    };
    
    export default App;
    
  2. Start your React application in a new terminal window:

    npm start
    

Conclusion

Congratulations! You have successfully built a web application using React connected to Azure Cosmos DB. This tutorial covered the entire process from setting up Cosmos DB to creating a React frontend that fetches data from your backend.

As you continue to develop your application, consider expanding its features by adding forms for data entry, implementing user authentication, or exploring other functionalities provided by Cosmos DB.

For more advanced topics, check out the Azure Cosmos DB documentation and the React documentation to enhance your web development skills.

Happy coding!

Another screenshot from the tutorial
Another view from the tutorial

Connect with SkillBakery Studios

Explore more tutorials, tools, and resources:

Posted by SkillBakery Studios

No comments:

Post a Comment

Post Top Ad