#Caching in App router

1 messages · Page 1 of 1 (latest)

blazing epochBOT
#

Hi @queen arch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can create a middleware in the App Router for caching. Below is an example of how you can set the Cache-Control header using middleware in Next.js:

// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const response = NextResponse.next();
  response.headers.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=59');
  return response;
}

This approach is similar to the one mentioned in the Github Issue #50914 (https://github.com/vercel/next.js/issues/50914) where a user successfully set the Cache-Control header in middleware.

However, be aware that setting headers in middleware can sometimes be tricky because the middleware runs before the page is rendered. This means that certain headers might be overwritten or not behave as expected. For more complex scenarios, you might need to consider additional configurations or workarounds.

For more information on caching mechanisms in Next.js, you can refer to the Next.js Caching Documentation (https://nextjs.org/docs/app/building-your-application/caching).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@queen arch kapa.ai is still learning and improving, please let us know how it did by reacting below

queen arch
#

@blazing epoch ok, I wonder can we apply this middleware to only homepage?

blazing epochBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, you can apply the middleware to only the homepage by using the matcher option in the middleware configuration. Here is how you can do it:

// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const response = NextResponse.next();
  response.headers.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=59');
  return response;
}

// Apply the middleware only to the homepage
export const config = {
  matcher: '/',
};

This configuration ensures that the middleware is only applied to the homepage route (/). The matcher option is used to specify the paths where the middleware should be active.

For more details on how to use the matcher option, you can refer to the Next.js Middleware Documentation (https://nextjs.org/docs/app/api-reference/file-conventions/middleware#matcher).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: