ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Router Caching in NextJS

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='21' AND `tutorial_submenu`='1762' AND `tutorial_status`=1 LIMIT 1

Router Caching in NextJS

🚀 Router Caching in Next.js

Router Caching in Next.js helps optimize navigation and improve page load speeds by storing previously visited pages, reducing redundant network requests, and minimizing re-renders.


📌 1. Why Use Router Caching?

✔️ Improves navigation speed by avoiding unnecessary data fetching
✔️ Reduces API calls when switching between pages
✔️ Enhances performance by caching pre-rendered pages


📌 2. Automatic Caching in Next.js

By default, Next.js caches pre-rendered pages for optimization.

🔹 Static Pages are Cached Automatically

  • Pages built with getStaticProps() are cached and served instantly.

  • No re-fetching unless manually invalidated.

javascript

<nav> import useSWR from "swr";const fetcher = (url) => fetch(url).then((res) => res.<p>Error loading data<p>Loading...<pre>{JSON.stringify(data, null, 2)}</pre>;}

Caches API responses for faster page loads
Avoids re-fetching data when revisiting the page


📌 5. Full Route Caching with Middleware

Use middleware caching to intercept requests and serve cached pages.

🔹 Example: Implementing Router Cache in Middleware

javascript

import { NextResponse } from "next/server";const cache = new Map();export function middleware(req) { const { pathname } = req.nextUrl; if (cache.has(pathname)) { return NextResponse.json(cache.get(pathname)); // Return cached response } const response = NextResponse.next(); cache.set(pathname, response.clone()); // Store response in cache return response;}

Caches full pages for quick responses
Prevents redundant requests to the server


📌 6. Custom Cache-Control Headers

Manually control router caching using HTTP headers.

🔹 Example: Setting Cache Headers in API Routes

javascript

export default function handler(req, res) { res.setHeader("Cache-Control", "s-maxage=3600, stale-while-revalidate=600"); res.status(200).json({ message: "Cached for 1 hour" });}

Caches response for 1 hour (s-maxage=3600)
Allows stale data while fetching new data (stale-while-revalidate)


📌 7. Router Caching in next.config.js

Define custom caching rules for your Next.js app.

🔹 Example: Cache API Responses Globally

javascript

module.exports = { async headers() { return [ { source: "/api/:path*", headers: [ { key: "Cache-Control", value: "s-maxage=600, stale-while-revalidate" }, ], }, ]; },};

Caches all API requests for 10 minutes
Prevents unnecessary re-fetching


🚀 Summary: Router Caching Methods

MethodUse CaseCache Type
getStaticProps()Cache pre-rendered pagesISR (Static)
next/link prefetchingPreloads linked pagesClient-side
SWRCache API requestsClient-side
Middleware CacheFull page cachingServer-side
Cache-Control HeadersFine-grained cachingServer-side
next.config.js HeadersGlobal caching rulesServer-side

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql