Introducing a lightweight utility for Next.js that enhances performance by simplifying server-side caching. With browser session scoping and deduplication, it ensures efficient management of server queries, reducing redundancy and improving load times without complexity. Optimize your application's responsiveness seamlessly.
Sesh is a simplified server-side caching utility tailored for Next.js developers seeking a reliable, efficient means to cache server-side data fetching without the complexities and risks associated with using unstable_cache
. By incorporating browser sessions to scope caching, Sesh ensures that users receive fresh data, safeguarding against data leakage across sessions.
Key Features
- Browser Session-Scoped Caching: Creates session-specific caches to prevent data leakage between users.
- Automatic Cache Invalidation: Refreshes data seamlessly upon page refresh or tab focus recovery.
- Deduplication: Minimizes redundant data fetching within the same render cycle leveraging React's caching capabilities.
- Familiar Usage Patterns: Designed to feel familiar for those accustomed to popular data-fetching libraries.
- Optimized for Next.js: Integrates smoothly with Next.js's features like streaming and Suspense while maintaining simple caching logic.
Why Choose Sesh?
Sesh effectively bridges the gaps left by existing Next.js caching methods, addressing common pitfalls:
- Risks with
unstable_cache
: Avoid the dangers of caching errors, data leakage, and serving stale data associated with misusingunstable_cache
. - Limitations of Fetch Cache: Navigate around the constraints of built-in fetch cache when implementing the latest Next.js features.
- Inappropriate Use of Server Actions: Recognize that Server Actions are meant for mutations rather than data fetching, ensuring a safer data access approach.
How Does Sesh Work?
- When Cookies Are Enabled: Automatically generates a unique session ID stored in cookies, allowing the caching mechanism to maintain scoping across a user's session.
- When Cookies Are Disabled: Safeguards against data leakage by avoiding
unstable_cache
, while still providing caching capabilities within the render cycle.
Example Usage
Wrapping your query functions with Sesh is simple:
import { query } from 'sesh-cache-helper';
export const getUserById = query(async (userId: string) => {
const user = await prisma.user.findUnique({
where: { id: userId },
});
return user;
}, userId => `getUserById-${userId}`);
Use your wrapped queries straightforwardly in server components:
import { getUserById } from '../../../queries';
export default async function UserPage({ params }) {
const user = await getUserById(params.userId);
return user ? <h1>{user.name}</h1> : <div>User not found.</div>;
}
With Sesh, enhance the performance and reliability of your Next.js applications without the worry of common caching pitfalls. Explore the full documentation in the repository and start integrating today!