Search code examples
vue.jsnuxt.jsvuejs3nuxtjs3

Nuxt 3 How to add Cache Control to generated static files


I am creating SSR project with Nuxt 3. I am thinking to add Cache-Control Header to generated static files in .output/_nuxt directory.

I tried below code server/middleware/cache-control.ts

export default defineEventHandler((event) => {
  let res = event.res
  const year = 31536000
  const tenmin = 600
  const url = event.req.url
  const maxage = url.match(/(.+)\.(jpg|jpeg|gif|css|png|js|ico|svg|mjs)/) ? year : tenmin
  res.setHeader('Cache-Control', `max-age=${maxage} s-maxage=${maxage}`);
})

But, it does not work.

enter image description here

How to add Cache-Control to the generated static files?


Solution

  • I figure out by myself. Adding bellow code to nuxt.config.js will append cache-control to your static files. Thank you for your support!

    export default defineNuxtConfig({
      nitro: {
        routeRules: {
          "/img/**": { headers: { 'cache-control': `public,max-age=${year},s-maxage=${year}` } },
          "/_nuxt/**": { headers: { 'cache-control': `public,max-age=${year},s-maxage=${year}` } },
        }
      }
    })