Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Data Fetching Strategies in Next.js

1. Server-Side Rendering (SSR)

Server-Side Rendering is a data fetching strategy where the HTML is generated on the server for each request. This allows for optimal SEO and faster initial page load.

export async function getServerSideProps() {
    const res = await fetch('https://api.example.com/data');
    const data = await res.json();

    return { props: { data } };
}

2. Static Site Generation (SSG)

Static Site Generation generates HTML at build time. This is ideal for pages that can be pre-rendered and do not change frequently, improving performance and reducing server load.

export async function getStaticProps() {
    const res = await fetch('https://api.example.com/data');
    const data = await res.json();

    return { props: { data } };
}

3. Client-Side Rendering (CSR)

Client-Side Rendering fetches data on the client-side after the initial render. This can lead to a more dynamic experience but may impact SEO.

import { useEffect, useState } from 'react';

    const MyComponent = () => {
        const [data, setData] = useState(null);

        useEffect(() => {
            fetch('https://api.example.com/data')
                .then(res => res.json())
                .then(data => setData(data));
        }, []);

        return 
{data ? JSON.stringify(data) : 'Loading...'}
; };

4. API Routes

Next.js allows you to create API routes to handle backend logic. These routes can be used for data fetching in your applications.

export default function handler(req, res) {
    const data = { message: 'Hello from API' };
    res.status(200).json(data);
}

5. Best Practices

To maximize performance and usability, consider the following strategies:

  • Use SSG for static content to improve load times.
  • Implement SSR for dynamic content that needs to be up-to-date.
  • Employ CSR for interactive elements that do not rely on SEO.
  • Utilize API routes to manage backend logic effectively.

FAQ

What is the difference between SSR and SSG?

SSR generates HTML on each request while SSG generates HTML at build time.

When should I use CSR?

CSR is suitable for applications with highly interactive components that do not need to be indexed by search engines.

Can I use both SSR and SSG in the same application?

Yes, you can use SSR for some pages and SSG for others based on your content needs.