Caching and Server-side Rendering

Overview

Caching in server-side rendering (SSR) involves storing and retrieving frequently used data on the server to improve the performance and load times of dynamically generated web pages. When a request is made to the server for a SSR page, the server can check if the requested data is already available in its cache. If the data is found in the cache, it can be directly used to generate the response without having to fetch it from the original source again. This can significantly reduce the time and resources needed to generate the SSR page, resulting in faster response times and improved performance.

How to use

Here we use caching and server-side rendering. The installation method is as follows below.

Step 1: Configure Caching

Next.js introduces built-in caching capabilities using React Query. You can configure caching by creating a new file react-query-config.ts in src/services/react-query directory with the following code:

import { QueryClient, QueryClientOptions } from 'react-query';

export const queryClientConfig: QueryClientOptions = {
  defaultOptions: {
    queries: {
      staleTime: 5000, // Set stale time to 5 seconds
      cacheTime: 30000, // Set cache time to 30 seconds
    },
  },
};

export const queryClient = new QueryClient(queryClientConfig);

Step 2: Use React Query for Data Fetching

You can now use React Query to fetch data in your Next.js components. Here's an example of how you can use React Query with TypeScript in a Next.js component:

import { useQuery } from 'react-query';
import { queryClient } from '@/services/react-query-config';

const HomePage = () => {
  // Fetch data using React Query
  const { data, error, isLoading } = useQuery('/api/posts', async () => {
    const res = await fetch('/api/posts');
    return res.json();
  });

  if (error) {
    return <div>Error fetching data</div>;
  }

  if (isLoading) {
    return <div>Loading data...</div>;
  }

  // Render data
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post: any) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default HomePage;

Step 3: Enable Server-side Rendering (SSR)

Next.js also introduces built-in support for server-side rendering (SSR) using the getServerSideProps function. You can use it to fetch data and pass it as props to your Next.js components. Here's an example:

import { GetServerSideProps } from 'next';
import { queryClient } from '../react-query-config';

const HomePage = ({ posts }: { posts: any[] }) => {
  // Render data
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map((post: any) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export const getServerSideProps: GetServerSideProps = async () => {
  // Fetch data on the server
  await queryClient.prefetchQuery('/api/posts'); // Prefetch data with React Query
  const posts = queryClient.getQueryData('/api/posts'); // Get the data from the cache

  return {
    props: {
      posts,
    },
  };
};

export default HomePage;

Step 4: Add Caching and SSR to Other Pages

You can repeat Steps 3 and 4 to.

Last updated