#how to CACHE with nextresponse in an api route

1 messages · Page 1 of 1 (latest)

modern raft
#

how to CACHE with nextresponse in an api route

compact sequoiaBOT
#

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

#

You can cache responses in Next.js API routes by setting the Cache-Control header using the res.setHeader method. Here's an example:

import type { NextApiRequest, NextApiResponse } from 'next'
 
type ResponseData = {
  message: string
}
 
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.setHeader('Cache-Control', 's-maxage=86400')
  res.status(200).json({ message: 'Hello from Next.js!' })
}

In this example, the s-maxage=86400 directive tells the cache to store the response for 86400 seconds (1 day).

You can also use the stale-while-revalidate directive, which allows the cache to serve stale content while it revalidates the cache in the background:

export default function handler(req, res) {  
  res.setHeader('Cache-Control', 's-maxage=600, stale-while-revalidate=30') // set caching header  
  res.status(200).json({ name: 'John Doe' })
}

In this case, the cache will store the response for 600 seconds (10 minutes), and if a request is made after this time, it will serve the stale content while it revalidates the cache in the background for 30 seconds.

If you need to apply the header to multiple paths, you can use the Next.js headers configuration in next.config.js:

module.exports = {  
  async headers() {    
    return [      
      {        
        source: '/example/:id',        
        headers: [          
          {            
            key: 'cache-control',            
            value: 's-maxage=600, stale-while-revalidate=30',          
          },        
        ],      
      },    
    ]  
  },
}

In this example, the cache header is applied to all paths that match the pattern '/example/:id'.