How to Add Headers in Nginx to Solve Cache Issues for Gatsby.js and Other Sites

Table Of Contents
Introduction
Caching is crucial for improving website performance, but sometimes it can cause problems, especially when users see outdated content. For static sites like those built with Gatsby.js, proper cache management is essential to ensure users always receive the latest content without requiring a hard refresh (Ctrl + F5).
In this blog post, we’ll walk through how to configure Nginx to add headers that solve caching issues. This guide applies not only to Gatsby.js sites but also to other static and dynamic sites.
Why Headers Matter for Caching
When a browser requests resources from your server, it relies on caching headers to decide whether to fetch a new version or use a cached one. The wrong caching headers can cause the browser to use stale files, leading to:
- Outdated content
- Broken functionality
- New markdown (.md) files have not appeared.
Adding the right headers in Nginx ensures that:
- Critical resources (like HTML) are always fresh.
- Static assets (like CSS and JS) are cached for longer durations but updated when their content changes.
- The markdown (.md) files are not updated.
The Solution: Configuring Nginx Headers
1. Add Cache-Control Headers
The Cache-Control header tells browsers how long they can cache a resource. For Gatsby.js and similar frameworks, use:
- No caching for HTML files: These files must always be fetched fresh to ensure the latest content is displayed.
- Long-term caching for static assets: Files like
app-abc123.js(which include content hashes in filenames) can be cached for a long time because the filename changes when the content changes.
2. Example Nginx Configuration
Here’s an example Nginx configuration file to manage caching effectively:
server {listen 80;server_name yourdomain.com;# Root directory for your Gatsby siteroot /path/to/your/site/public;index index.html;# HTML files - no cachinglocation / {add_header Cache-Control "no-cache, no-store, must-revalidate";add_header Pragma "no-cache";add_header Expires 0;try_files $uri /index.html;}# Static assets - cache for a yearlocation ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|svg|otf)$ {expires 1y;access_log off;add_header Cache-Control "public, max-age=31536000, immutable";}}
Key Points in the Configuration
HTML Files:
Cache-Control: no-cache, no-store, must-revalidate: Ensures browsers always fetch fresh HTML.Pragma: no-cacheandExpires 0: Compatibility with older browsers.
Static Assets (CSS, JS, Images, Fonts):
Cache-Control: public, max-age=31536000, immutable: Allows caching for one year. Theimmutabledirective tells browsers the file won’t change, reducing unnecessary network requests.
try_files: Ensures that if the requested file doesn’t exist, Nginx serves
index.html(important for single-page applications like Gatsby).
Step-by-Step Guide to Apply These Headers
Step 1: Edit Your Nginx Configuration File
Locate the Nginx configuration file for your site, typically found in:
/etc/nginx/sites-available/yourdomain/etc/nginx/conf.d/yourdomain.conf
Open the file using a text editor:
sudo nano /etc/nginx/sites-available/yourdomain
Step 2: Add the Header Configuration
Paste the above configuration inside the server block for your site.
Step 3: Test the Nginx Configuration
Before restarting Nginx, ensure there are no syntax errors:
sudo nginx -t
Step 4: Reload Nginx
Apply the changes by reloading Nginx:
sudo systemctl reload nginx
How This Solves Cache Problems
For Gatsby.js Sites
- Dynamic Content (HTML): Browsers will always fetch the latest HTML, ensuring updates to your Markdown files or other content appear immediately.
- Static Assets (CSS, JS): Static files are cached for a long time but include content hashes in their filenames (e.g.,
styles-abc123.css). This ensures browsers fetch a new file when the content changes, avoiding stale assets.
For Other Static/Dynamic Sites
- Prevents browsers from caching critical files (like HTML).
- Ensures long-term caching for static assets to improve performance without risking outdated resources.
Verifying the Headers
1. Check with Browser Developer Tools
- Open your website in a browser.
- Press
F12to open Developer Tools. - Go to the Network tab and refresh the page.
- Click on the request for your HTML or static files (e.g.,
/index.htmlorapp-abc123.js). - Look for the response headers:
For HTML:
Cache-Control: no-cache, no-store, must-revalidatePragma: no-cacheExpires: 0For Static Assets:
Cache-Control: public, max-age=31536000, immutable
2. Check with Curl
Run the following command to inspect the headers:
curl -I http://yourdomain.com
Example output for HTML files:
HTTP/1.1 200 OKCache-Control: no-cache, no-store, must-revalidatePragma: no-cacheExpires: 0
Conclusion
Proper caching headers in Nginx are critical for solving cache issues in Gatsby.js and other sites. By following this guide, you can ensure that:
- Users always receive the latest content without needing a hard refresh.
- Static assets are cached effectively, improving performance and reducing server load.
This approach balances performance and freshness, ensuring an excellent user experience.
Feedback and Questions
Your insights drive us! For any questions, feedback, or thoughts, feel free to connect:
- Email: shady@shadynagy.com
- Twitter: @ShadyNagy_
- LinkedIn: Shady Nagy
- GitHub: ShadyNagy
If you found this guide beneficial, don’t hesitate to share it with your network. Until the next guide, happy coding! 🚀







