Junior
Where is it better to perform backend requests?
sobes.tech AI
Answer from AI
It is best to perform requests to the backend using asynchronous methods in the code:
-
On the client side (in the browser):
- Using the
fetchAPI or a library likeAxios. - Suitable for interactive user actions, dynamic data loading, form submissions.
- Allows creating SPAs (Single Page Applications).
- Implemented in JavaScript/TypeScript.
// Example with fetch async function fetchData() { try { const response = await fetch('/api/data'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } - Using the
-
On the server side (for example, when using SSR/SSG frameworks):
- In frameworks like Next.js or Nuxt.js (for React and Vue respectively).
- Data can be fetched during build time (SSG) or on each request (SSR).
- Improves SEO and performance (less "white screen"), as the page is rendered with data.
- Helps avoid CORS issues.
- Examples of methods in Next.js:
getStaticProps,getServerSideProps.
// Example with Next.js (getServerSideProps) export async function getServerSideProps(context) { const res = await fetch('https://api.example.com/data'); const data = await res.json(); if (!data) { return { notFound: true, // Render 404 page }; } return { props: { data }, // Pass data as props to the page component }; }
The choice depends on the required interactivity, SEO needs, application type (SPA, MPA), and the framework used. Often, a combination of these approaches is used.