Server-Side Caching for Next.js – Sesh

Simplify Next.js server-side caching with Sesh. Prevent data leaks, optimize performance, and manage browser sessions effortlessly.

Sesh is a lightweight utility library created for Next.js developers needing a simple and secure way to cache server-side data. It addresses the common problems of data leakage and stale data associated with directly using unstable_cache. Sesh leverages browser sessions to scope the cache so that each user receives fresh, relevant data.

This library focuses on improving the data-fetching process within server components. It allows you to use Next.js features like streaming and Suspense without worrying about complex caching strategies. Sesh also helps avoid common caching errors by providing a safe, user-friendly approach to server-side caching in Next.js applications.

Features

🔒 Browser Session-Scoped Caching: Ensures data remains isolated per user session, preventing cross-user data contamination

🔗 Next.js Optimization: Fully compatible with Next.js streaming and Suspense features

🛡️ Safe Caching Mechanism: Mitigates risks associated with improper cache implementation

🔄 Automatic Cache Invalidation: Dynamically serves fresh data during page refreshes and tab focus changes

Render Cycle Deduplication: Eliminates redundant data fetching within the same rendering process

Familiar Patterns: Built with inspiration from popular data-fetching libraries, making it easy to adopt for developers

Use Cases

  • E-commerce Product Catalogs. Web stores can leverage Sesh to cache product information, reducing database queries and improving page load times without risking data staleness.
  • Dashboard Applications. Enterprise dashboards benefit from session-scoped caching, ensuring each user sees personalized, up-to-date information without performance overhead.
  • Content Management Systems. CMS platforms can implement efficient content retrieval strategies, minimizing redundant database calls while maintaining data freshness.
  • User Profile Management. Applications requiring frequent user data access can optimize performance through intelligent, session-based caching mechanisms.
  • API Integration Platforms. Third-party API integrations can reduce external request frequencies through sophisticated client-side caching techniques.

Installation

Install Sesh using npm, Yarn, or pnpm:

npm install sesh-cache-helper
yarn add sesh-cache-helper
pnpm add sesh-cache-helper

Usage

1. Import the query function from sesh-cache-helper and wrap your asynchronous data-fetching functions. A cache key function must also be provided.

// queries.ts
import { query } from 'sesh-cache-helper';
import { prisma } from './prismaClient';
export const getUserById = query(
  async (userId: string) => {
    const user = await prisma.user.findUnique({
      where: { id: userId },
    });
    return user;
  },
  (userId) => `getUserById-${userId}`
);

2. Call your wrapped query functions within your server components.

// app/users/[userId]/page.tsx
import { getUserById } from '../../../queries';
export default async function UserPage({ params }) {
  const user = await getUserById(params.userId);
  if (!user) {
    return <div>User not found.</div>;
  }
  return (
    <div>
      <h1>{user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  );
}

3. Include the useBrowserSessionId hook in your root layout or a top-level client component to set up the browser session ID.

// app/layout.tsx
'use client';
import { useBrowserSessionId } from 'sesh-cache-helper';
export default function RootLayout({ children }) {
  useBrowserSessionId();
  return (
    <html>
      <body>{children}</body>
    </html>
  );
}

4. You can control cookie usage via the hasDisabledCookies parameter, which stops unstable_cache usage, improving data safety at the cost of potential performance.

// app/layout.tsx
'use client';
import { useBrowserSessionId } from 'sesh-cache-helper';
export default function RootLayout({ children }) {
  useBrowserSessionId({ hasDisabledCookies: true }); // Disable cookies
  return (
    <html>
      <body>{children}</body>
    </html>
  );
}

FAQ

Q: Why does Sesh use unstable_cache?
A: unstable_cache is the only way to cache data fetching in Next.js server components without creating extra API endpoints. Sesh uses it to provide a practical solution until a stable API is released.

Q: Why create Sesh when there are existing solutions like SWR or React Query?
A: SWR and React Query are excellent libraries for client-side data fetching and caching. However, they don’t address server-side caching in Next.js server components without creating API endpoints. Sesh fills this specific gap by simplifying server-side caching directly within server components.

Q: Is Sesh suitable for production environments?
A: Yes, the library has been tested in production and offers configurable options to manage performance and compliance requirements.

Q: What performance overhead does Sesh introduce?
A: The performance impact is minimal, with session ID generation being a lightweight operation that ensures data freshness.

Q: What happens when cookies are disabled?
A: Sesh bypasses unstable_cache when cookies are disabled, relying on React’s cache. This ensures the application functions correctly with the tradeoff of reduced performance.

Q: Is Sesh compliant with cookie laws?
A: Sesh can be configured to comply with European regulations. Session IDs are essential for the service and may fall under the “strictly necessary” exemption. Implement consent mechanisms if needed.

Q: Does Sesh simplify server-side caching?
A: Yes, Sesh simplifies caching by abstracting the complexities of unstable_cache. It provides a straightforward API, reduces boilerplate, and minimizes potential errors.

Preview

Bart Proost

Bart Proost

Leave a Reply

Your email address will not be published. Required fields are marked *