How to Connect Frontend and Backend: Complete Beginner's Guide
Master the fundamentals of frontend-backend communication using REST APIs, HTTP requests, and practical code examples. Learn how to build full-stack applications that handle user interactions, process data, and communicate securely.
How to connect frontend and backend: Frontend → HTTP Request → Backend API → Process Data → Database → JSON Response → Frontend Display. The frontend uses JavaScript fetch() to send requests to backend endpoints, and the backend returns data that the frontend displays to users.
Table of Contents
- What Does Connecting Frontend and Backend Mean?
- Frontend vs Backend: Responsibilities
- What Is an API?
- How Frontend Communicates With Backend
- Step-by-Step: Building Your First Connection
- Understanding JSON
- Sending Data From Frontend to Backend
- CORS and Cross-Origin Requests
- Common Errors and How to Fix Them
- Deployment and Production
- Connection Checklist
- Frequently Asked Questions
What Does Connecting Frontend and Backend Mean?
Connecting frontend and backend means allowing the user interface to communicate with the server.
When you build a website with login functionality, database storage, user accounts, or dynamic data, the frontend needs to communicate with the backend.
Here's the complete flow:
User Interaction
User enters data in the frontend form
HTTP Request
Frontend sends data to backend API endpoint
Backend Processing
Backend validates, processes, and stores data
Database Operation
Backend interacts with database if needed
JSON Response
Backend sends response back to frontend
Display Result
Frontend displays result to user
Frontend vs Backend: What's the Difference?
What Is the Frontend?
The frontend is what users see and interact with. Common technologies include HTML, CSS, JavaScript, React, Vue, and Angular.
- Displays user interface
- Collects user input
- Makes API requests
- Handles user interactions
- Displays data from backend
What Is the Backend?
The backend runs on a server and handles application logic. Popular frameworks include Node.js, Express, Django, Flask, Spring Boot, and .NET.
- Processes requests
- Validates data
- Manages databases
- Handles authentication
- Executes business logic
What Is an API?
An API (Application Programming Interface) is a set of rules that allows different software to communicate.
| HTTP Method | Purpose | Example Endpoint |
|---|---|---|
| GET | Retrieve data | /api/users/1 |
| POST | Create/send data | /api/users |
| PUT | Update entire resource | /api/users/1 |
| PATCH | Partially update data | /api/users/1 |
| DELETE | Delete data | /api/users/1 |
How Frontend Communicates With Backend
JavaScript provides several ways to make HTTP requests to backend servers.
The Fetch API
The Fetch API is the modern way to make HTTP requests from the browser. Here's a simple example:
fetch("http://localhost:5000/api/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
In this example:
- fetch() sends a GET request to the backend
- .then(response => response.json()) parses the response as JSON
- .then(data => ...) handles the parsed data
- .catch() handles errors
Building Your First Frontend-Backend Connection
Let's build a simple project with Node.js and Express on the backend, and HTML/CSS/JavaScript on the frontend.
Create Backend with Express
Create a folder and initialize Node.js project:
npm init -y
npm install express cors
Create server.js:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
app.get("/api/message", (req, res) => {
res.json({
message: "Hello from the backend!"
});
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
Create Frontend HTML
Create index.html:
<!DOCTYPE html>
<html>
<head>
<title>Frontend-Backend Connection</title>
</head>
<body>
<h1>Frontend and Backend Connection</h1>
<button onclick="getMessage()">Get Message</button>
<p id="result"></p>
<script src="script.js"></script>
</body>
</html>
Add JavaScript to Frontend
Create script.js:
function getMessage() {
fetch("http://localhost:5000/api/message")
.then(response => response.json())
.then(data => {
document.getElementById("result").innerText =
data.message;
})
.catch(error => {
console.error("Error:", error);
});
}
Test Your Connection
Start the backend:
node server.js
Open index.html in your browser and click the button. You should see "Hello from the backend!"
Understanding JSON
JSON (JavaScript Object Notation) is the standard format for exchanging data between frontend and backend.
JSON Structure
{
"name": "Pooja",
"email": "pooja@example.com",
"age": 24,
"skills": ["Java", "Python", "SQL"]
}
JSON uses key-value pairs and is language-independent, making it perfect for API communication.
JSON in Frontend-Backend
// Frontend sends
{
"name": "Pooja",
"email": "pooja@example.com"
}
// Backend receives and
// responds with
{
"success": true,
"userId": 123,
"message": "User created"
}
Sending Data From Frontend to Backend
Use POST requests to send data from the frontend to the backend for storage or processing.
Frontend: Send POST Request
function registerStudent() {
const student = {
name: "Pooja",
email: "pooja@example.com"
};
fetch("http://localhost:5000/api/students", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(student)
})
.then(response => response.json())
.then(data => {
console.log("Response:", data);
})
.catch(error => console.error(error));
}
Backend: Receive and Process
app.post("/api/students", (req, res) => {
const student = req.body;
console.log(student);
// Validate and store data...
res.json({
message: "Student created successfully",
student: student
});
});
Understanding CORS
CORS (Cross-Origin Resource Sharing) allows browsers to make requests from one origin to another.
CORS Error Example
Frontend at localhost:3000 tries to access backend at localhost:5000
Access to fetch at 'http://localhost:5000'
from origin 'http://localhost:3000'
has been blocked by CORS policy
CORS Solution
Enable CORS on the backend:
const cors = require("cors");
app.use(cors({
origin: "http://localhost:3000"
}));
cors() without arguments in
production. Always specify allowed origins for security.
Common Frontend-Backend Connection Errors
Understanding these common errors will help you debug faster.
Backend Server Not Running
Problem: Frontend calls backend URL but backend isn't running.
Solution: Start the backend server
with node server.js
Wrong API URL
Problem: Frontend calls
/api/users but backend endpoint is
/api/students
Solution: Verify the backend endpoint and update the frontend URL.
Wrong HTTP Method
Problem: Backend expects POST but frontend sends GET by default.
Solution: Add
method: "POST" in fetch options.
Wrong Port Number
Problem: Backend runs on port 8080 but frontend calls port 5000.
Solution: Check backend console output for correct port.
Missing JSON Parsing
Problem: Backend can't read JSON from frontend.
Solution: Add
app.use(express.json()) in backend.
Database Connection Failed
Problem: Frontend and backend work but database connection fails.
Solution: Check database is running and connection string is correct.
Frontend-Backend After Deployment
When you deploy your application, URLs change.
Development Environment
Frontend: localhost:3000
Backend: localhost:5000
API Call:
http://localhost:5000/api/users
Production Environment
Frontend: myapp.com
Backend: api.myapp.com
API Call:
https://api.myapp.com/api/users
Update API URLs for Production
Instead of hard-coding URLs, use environment variables:
// Development
const API_URL = "http://localhost:5000";
// Production
const API_URL = "https://api.myapp.com";
// Or use environment variables
const API_URL = process.env.REACT_APP_API_URL;
Frontend-Backend Connection Checklist
Use this checklist to verify everything is working:
Frontend Checklist
- ✓ Frontend is running
- ✓ API URL is correct
- ✓ HTTP method matches backend
- ✓ Request body is valid JSON
- ✓ Response is being handled
- ✓ Error handling is in place
Backend Checklist
- ✓ Server is running
- ✓ API endpoint path is correct
- ✓ JSON parsing is enabled
- ✓ CORS is configured
- ✓ Response status code is correct
- ✓ Error handling is implemented
Database Checklist
- ✓ Database is running
- ✓ Connection string is correct
- ✓ Credentials are secure
- ✓ Tables exist
- ✓ Permissions are set
- ✓ Connection pooling works
Frequently Asked Questions
Common questions about frontend-backend connections.
How do I connect frontend and backend?
You connect frontend and backend using HTTP requests to backend API endpoints. The frontend sends requests using JavaScript fetch(), and the backend processes the request and returns a response, commonly in JSON format.
What is an API?
An API (Application Programming Interface) provides a way for different parts of an application to communicate. Frontend-backend communication typically uses REST APIs with endpoints that accept HTTP methods like GET, POST, PUT, and DELETE.
Can HTML and CSS connect directly to a backend?
HTML and CSS create the user interface, but JavaScript is commonly used to make API requests from the browser to the backend. JavaScript uses the Fetch API or other HTTP clients to communicate with backend services.
Why am I getting a CORS error?
A CORS error occurs when the browser makes a cross-origin request and the backend doesn't provide appropriate CORS response headers for that frontend origin. Fix CORS on the backend by configuring the cors() middleware in Express or similar settings in other frameworks.
Can React connect directly to MySQL?
A React application running in the browser should generally not connect directly to MySQL. A backend server should sit between the React application and the database to handle security, validation, and business logic.
How do I send data from frontend to backend?
Use the Fetch API with a POST request. Include the data in the request body as JSON, set the appropriate headers, and the backend receives it via req.body after parsing the JSON with middleware like express.json().
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used to exchange data between frontend and backend. It's human-readable and language-independent, making it ideal for API communication.
How do I handle errors in API requests?
Check the response status code using response.ok, handle promise rejections with .catch(), and implement error boundaries in React applications. Always validate API responses before using them.
How do I deploy a full-stack application?
Deploy the frontend to a hosting service like Vercel or Netlify, deploy the backend to a server like Heroku or AWS, configure the frontend to use the production backend URL, and ensure both use HTTPS in production.
What are common connection errors?
Common errors include backend not running, wrong API URL, incorrect HTTP method, wrong backend port, missing JSON parsing middleware, database connection issues, and CORS configuration problems.
Ready to Build Full-Stack Applications?
Learn web development, backend frameworks, and database integration through practical projects and internships.
Explore Web Dev Internships →