Category: react
connect react with aws api gateway
Published on 15 Sep 2026
Explanation
Amazon API Gateway provides an HTTP entry point for backend services. A React application can call an API Gateway endpoint using fetch or a library such as Axios.
Code:
const response = await fetch( 'https://api.example.com/users' ); const users = await response();
Explanation
Keep API calls in a separate service module. This improves code organization and makes it easier to reuse API logic across multiple React components.
Code:
export async function getUsers() {
const response = await fetch(
`${import.meta.env.VITE_API_BASE_URL}/users`
);
if (!response.ok) {
throw new Error('Failed to load users');
}
return response();
}
Explanation
The useEffect hook can load data when a component is mounted. Manage loading, success, and error states so the user receives useful feedback.
Code:
useEffect(() => {
getUsers()
.then(setUsers)
.catch(setError)
.finally(() => setLoading(false));
}, []);
Explanation
React can send JSON data to an API Gateway endpoint using the POST method. Set the Content-Type header and serialize the JavaScript object with JSON.stringify.
Code:
await fetch(`${apiUrl}/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Praveen',
role: 'Developer'
})
});
Explanation
Browsers enforce the same-origin policy. Configure CORS in the API Gateway and backend so the deployed React domain is allowed to call the API.
Code:
Allowed origin example: https://www.example.com Avoid using '*' for sensitive production APIs. Allow only the methods and headers required by the application.