Caching Updates in Next.js 15

Sat Jun 01 2024

Introduction

Next.js 15 introduces several significant updates to caching mechanisms, providing developers with greater control and flexibility over how data is cached in their applications. These changes enhance performance, scalability, and user experience.

Default Uncached Fetch Requests

In Next.js 15, fetch requests are uncached by default. This ensures that data is always fresh and up-to-date, particularly important for dynamic applications where data changes frequently. However, developers can opt into caching based on their specific requirements.

fetch('https://api.example.com/data', { cache: 'no-store' });

The above code demonstrates a fetch request with no caching, ensuring that every request retrieves the latest data from the API.

Opt-In Caching for Fetch Requests

Developers can choose to cache fetch requests when appropriate. This is useful for data that does not change frequently, reducing load times and server requests.

fetch('https://api.example.com/data', { cache: 'force-cache' });

The force-cache option caches the response and serves it for subsequent requests, improving performance for static or infrequently changing data.

Client-Side Navigation Caching

Next.js 15 introduces caching updates for client-side navigations. By default, client-side navigations are now uncached, ensuring that users always see the most current content when navigating through the application.

Developers can still opt into caching for specific routes or data, providing flexibility to balance between performance and freshness of data.

Caching in GET Route Handlers

Similar to fetch requests, GET route handlers in Next.js 15 are uncached by default. This change ensures that responses are always fresh and reflect the latest data. Developers can opt into caching for specific use cases where data does not change frequently.

export default function handler(req, res) {
  res.setHeader('Cache-Control', 's-maxage=86400, stale-while-revalidate');
  res.json({ message: 'This response is cached for 24 hours' });
}

The example above shows how to set cache headers in a GET route handler to control caching behavior.

Conclusion

Next.js 15's caching updates provide developers with enhanced control over how data is cached, ensuring that applications deliver the latest content while optimizing performance. By defaulting to uncached fetch requests and client-side navigations, Next.js prioritizes data freshness, but also offers flexible caching options for specific use cases.

Further Reading

For more detailed information, visit the Next.js 15 RC blog post.