Sobes.tech
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:

  1. On the client side (in the browser):

    • Using the fetch API or a library like Axios.
    • 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);
      }
    }
    
  2. 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.

Where is it better to perform backend requests… - sobes.tech