Connecting Frontend with Backend (MERN)

Table of contents

No heading

No headings in the article.

Building a full-stack web application using the MERN (MongoDB, Express, React, Node.js) stack can be a great way way to create a scalable, responsive and maintainable application. However, connecting the frontend to the backend can be a challenging task. In this blog post, we will going through all the steps required to connect the frontend to the backend of a MERN app.

STEP 1: Firstly we set up the Backend

The first step in connecting the frontend to the backend is to set up the backend server. To do this, we will need to use Node.js and the Express framework. We will be using Mongoose like driver to connect the MongoDB database. (Mongoose is JS library used to connect the server with the database)

Create a new project directory and run the following command in terminal to initialize a new Node.js project:

npm init -y

Now, install the necessary dependencies:

npm install express mongoose cors

Now, we will create a new file named anyname.js in the root directory of your project. In this file, import the necessary dependencies and create a new Express application:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();

Next, set up the database connection using Mongoose:

mongoose.connect('mongodb://localhost/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB');
});

Lastly, set up the middleware:

app.use(cors());
app.use(express.json());

With all these our backend server setup is ready to handle request from client side.

STEP 2: Creating API endpoints

Creating API endpoints is an essential part of building a modern web application. These endpoints allow the frontend to interact with the backend server by sending requests and receiving responses.

The first step is to create a new file called "api.js" in the routes directory of our Node.js project. This file will contain the routes that handle CRUD (Create, Read, Update, Delete) operations for your application's data. To get started, import the necessary dependencies and create a new router:

const express = require('express');
const router = express.Router();

Once we have created the router, we can start defining endpoints for handling CRUD operations. For example, to create a new resource, you can define the following endpoint:

router.post('/resources', (req, res) => {
  res.json({ success: true });
});

Once we have defined the endpoints, we need to use the router in the main anyname.js file of your Node.js project. To do this, add the following code to your anyname.js file:

const apiRouter = require('./routes/api');
app.use('/api', apiRouter);

This will allow our frontend to make requests to the API and receive responses from the backend server.

STEP 3: Now we can jump to Frontend Part

The next step is to create a frontend application using React. To get started, you can use tools like create-react-app or (react + vite).

Once we have created the project, you can navigate to the project directory and start the development server by running:

cd project-name
npm start

This will start the development server at http://localhost:3000.

STEP 4: Start making API Calls

With the frontend application running, you can now make API calls to the backend server to retrieve and manipulate data. To make API calls, you can use the fetch() function or a library like Axios.

We can define a function like this:

const getResources = async () => {
  const response = await fetch('/api/resources');
  const data = await response.json();
  return data;
}

STEP 5: Finally Update User Interface

Once we receive a response from the backend, we can update the UI of our frontend application to display the data. For example, we can use the useState() hook to store the list of resources and update the UI when the list is changed:

import { useState, useEffect } from 'react';

function App() {
  const [resources, setResources] = useState([]);

  useEffect(() => {
    const fetchResources = async () => {
      const data = await getResources();
      setResources(data);
    };

    fetchResources();
  }, []);

  const handleCreateResource = async (resourceData) => {
    const newResource = await createResource(resourceData);
    setResources([...resources, newResource]);
  };

  const handleDeleteResource = async (id) => {
    await deleteResource(id);
    setResources(resources.filter(resource => resource._id !== id));
  };

  return (
    <div>
      <h1>Resources</h1>
      <ResourceList resources={resources} onDelete={handleDeleteResource} />
      <ResourceForm onCreate={handleCreateResource} />
    </div>
  );
}

I hope this blog post is helpful in showing you how to connect the frontend to the backend in a MERN app.

Thank you.