Request Cache and Redirect
You'll learn: How to control browser caching and automatic redirect following when making fetch requests.
When you use the Fetch API, the browser makes decisions about whether to use cached responses and whether to automatically follow redirects. You can control both behaviors explicitly using the cache and redirect options on your Request object.
Understanding request.cache
The cache option tells the browser how aggressively to use cached responses. You've already seen cache options like 'default', 'reload', and 'no-cache' in earlier lessons. When creating a Request object, you can set this explicitly:
const request = new Request('https://api.example.com/data', {
cache: 'no-store' // Never use cache, always fetch fresh
});
fetch(request);
This is particularly useful when you need to ensure fresh data or when building offline-capable applications with specific caching strategies.
Understanding request.redirect
The redirect option controls what happens when the server responds with a redirect status code (like 301 or 302). Three values are available:
'follow'(default): Automatically follows redirects'error': Treats redirects as errors, rejecting the promise'manual': Returns the redirect response without following it
const request = new Request('https://example.com/old-page', {
redirect: 'error' // Don't follow redirects; throw an error instead
});
fetch(request)
.catch(err => console.log('Redirect or network error occurred'));
Use 'manual' when you need to inspect redirect responses yourself, or 'error' when redirects should be treated as failures in your application logic.
Key Takeaway: The cache and redirect options on Request objects give you fine-grained control over browser caching behavior and how automatic redirects are handled during network requests.