DEV Community

Cover image for React + Spring Boot: How to Communicate Frontend and Backend (Step-by-Step Guide)
Code Begun
Code Begun

Posted on

React + Spring Boot: How to Communicate Frontend and Backend (Step-by-Step Guide)

Building a React frontend and a Spring Boot backend separately is straightforward. But connecting them properly is where many developers encounter challenges.

Whether you're building a student management system, an e-commerce application, or a task management platform, understanding frontend-backend communication is an essential full-stack development skill.

In this tutorial, we'll explore how React communicates with Spring Boot, how to manage API requests, configure authentication, avoid unnecessary CORS configuration, and prepare the application for production.

1. Understand the architecture

Before writing code, understand how the frontend and backend communicate.

A typical React + Spring Boot application follows this architecture:

             User
               |
               v
         React Frontend
               |
               | HTTP Requests
               v
       Spring Boot REST API
               |
               v
          Service Layer
               |
               v
         Repository Layer
               |
               v
           Database
Enter fullscreen mode Exit fullscreen mode

React frontend:

  • Displays the user interface.
  • Collects user input.
  • Sends HTTP requests.
  • Displays responses from the backend.

Spring Boot backend:

  • Handles API requests.
  • Processes business logic.
  • Communicates with the database.
  • Returns responses in JSON format.

2. Create the Spring Boot REST API

Let's consider a student management application.

First, create a REST controller that exposes student-related endpoints.

@RestController
@RequestMapping("/api/students")
public class StudentController {

    @GetMapping
    public List<Student> getStudents() {
        return studentService.getAllStudents();
    }

    @PostMapping
    public Student addStudent(
            @RequestBody Student student) {
        return studentService.saveStudent(student);
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, we have two endpoints:

  • GET /api/students – Retrieves student information.
  • POST /api/students – Creates a new student.

The controller receives requests from React and communicates with the service layer.

3. Connect React with Spring Boot using Axios

React needs an HTTP client to communicate with backend APIs.

Axios is a commonly used option.

Install Axios:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Create a reusable API configuration:

import axios from "axios";

const api = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json"
  }
});

export default api;
Enter fullscreen mode Exit fullscreen mode

Using a relative API URL makes it easier to route requests through a development proxy or production reverse proxy.

4. Configure Vite Proxy for local development

One important thing to understand is that React and Spring Boot do not necessarily need separate public origins.

During local development, Vite can forward API requests to Spring Boot.

Open your vite.config.js file:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        changeOrigin: true
      }
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

Now, when React sends a request to:

api.get("/students");
Enter fullscreen mode Exit fullscreen mode

Vite forwards it to:

http://localhost:8080/api/students
Enter fullscreen mode Exit fullscreen mode

The browser communicates with the Vite development server, which proxies the request to Spring Boot.

This avoids unnecessary browser CORS configuration during local development.

5. Fetch data from Spring Boot

Now let's retrieve student information from the backend.

import { useEffect, useState } from "react";
import api from "./api";

function StudentList() {

  const [students, setStudents] = useState([]);

  useEffect(() => {
    api.get("/students")
      .then(response => {
        setStudents(response.data);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }, []);

  return (
    <div>
      <h2>Student List</h2>

      {students.map(student => (
        <p key={student.id}>
          {student.name}
        </p>
      ))}
    </div>
  );
}

export default StudentList;
Enter fullscreen mode Exit fullscreen mode

The process is simple:

  1. React sends a GET request.
  2. Vite forwards the request to Spring Boot.
  3. Spring Boot retrieves student information.
  4. The backend returns JSON data.
  5. React displays the response.

6. Send data from React to Spring Boot

Suppose a user wants to register a new student.

You can use an Axios POST request:

const addStudent = async (student) => {

  try {
    const response = await api.post(
      "/students",
      student
    );

    return response.data;

  } catch (error) {
    console.error("Unable to add student", error);
    throw error;
  }
};
Enter fullscreen mode Exit fullscreen mode

The backend receives the student details and processes them.

This approach is useful for registration forms, login pages, contact forms, and other application features.

7. Implement JWT authentication

Most real-world applications require authentication.

JWT (JSON Web Token) is commonly used to secure communication between frontend and backend.

The authentication process:

  1. User enters login credentials in React.
  2. React sends credentials to Spring Boot.
  3. Spring Boot validates the credentials.
  4. Backend generates an authentication token.
  5. React sends the token with subsequent protected API requests.
  6. Spring Security validates the token.

You can use Axios interceptors to attach authentication headers.

api.interceptors.request.use(config => {

  const token = localStorage.getItem("token");

  if (token) {
    config.headers.Authorization =
      `Bearer ${token}`;
  }

  return config;
});
Enter fullscreen mode Exit fullscreen mode

For production applications, use secure token storage and appropriate protection against token theft. An HttpOnly, Secure, SameSite cookie-based approach is another option.

8. Configure production deployment using a reverse proxy

The Vite proxy is useful for local development, but it should not be used as your production server.

In production, you can use Nginx, Caddy, or Traefik to serve the React frontend and route API requests to Spring Boot.

For example:

           https://example.com
                    |
                    v
              Nginx Server
                    |
             +------+------+
             |             |
             v             v
        React Files    /api Requests
                           |
                           v
                     Spring Boot
                       Port 8080
Enter fullscreen mode Exit fullscreen mode

Example Nginx configuration:

server {
    listen 80;
    server_name example.com;

    root /var/www/react-app;
    index index.html;

    location /api/ {
        proxy_pass http://localhost:8080;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For
                         $proxy_add_x_forwarded_for;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Enter fullscreen mode Exit fullscreen mode

With this architecture:

  • React serves the frontend.
  • Nginx routes API requests to Spring Boot.
  • Both are accessible through the same domain.
  • Browser-side cross-origin requests are generally avoided.

This is often a cleaner deployment architecture than configuring CORS for every frontend-backend interaction.

Note: CORS may still be required if other websites or origins access your backend directly.

9. Common problems during integration

Problem Possible solution
404 Not Found Verify API endpoint paths
401 Unauthorized Check authentication and JWT
Network error Check backend availability
Empty response Verify controller and service logic
Vite proxy error Verify Spring Boot URL and port
Production routing issue Check reverse proxy configuration

10. Final thoughts

Connecting React with Spring Boot is an important skill for full-stack developers.

Understanding REST APIs, Axios, HTTP requests, authentication, proxy configuration, and deployment will help you build applications where frontend and backend work together efficiently.

The best way to learn these concepts is by building a practical application such as a student management system, employee portal, or e-commerce platform.

Want to explore the complete React + Spring Boot integration guide?

We have also published a detailed tutorial covering frontend-backend communication, API configuration, authentication, and deployment.

Read the complete guide:

https://www.codebegun.com/blog/react-spring-boot-connect-frontend-backend

Top comments (0)