How would you connect a React front end to a Spring Boot REST API?
Answer
- Spring side:
@RestController returning JSON; configure CORS for the front-end origin (or serve both from the same origin); secure with Spring Security (JWT or session cookies). - React side: call endpoints with
fetch or axios inside useEffect or a data library (TanStack Query) and keep results in state. - Handle three states: loading, error, success; check
res.ok. - Auth: send the token in the
Authorization header or use HttpOnly cookies. - Dev: Vite dev server proxy to
localhost:8080; Prod: build static files and serve behind the same domain or a CDN. - Contract: agree on DTOs and error format; consider OpenAPI (springdoc) to generate typed clients.
Practice this question in Repaso