Home > Mobile >  Nuxt 3 How to add Cache Control to generated static files
Nuxt 3 How to add Cache Control to generated static files

Time:07-14

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?

CodePudding user response:

Never tried but there is a method inside useRequestEvent()

const headers = useRequestEvent()
headers.res.setHeader(...)

CodePudding user response:

Try to use the h3 function:

appendHeader(res, name, value)

Nuxt 3 works based on: https://github.com/unjs/h3

  • Related