Paulund

Optimizing Web Performance: A Detailed Guide to HTTP Caching with Nuxt3

HTTP caching allows you to store a response to a request allowing your browser to reuse stored responses for subsequent requests.

This gives you advantage of not having to refetch content from the origin server allowing your visitors to have faster response times.

You can quickly do this in your website applications by returning the HTTP header Cache-Control in the response.

With Nuxt3 it will automatically load all files in the server folder, you can create a middleware folder which will mean you can add headers in the response coming from the nuxt server.

Create a new file in server/middleware/cache-control.ts and add the following into the file.

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

This will check the url for images and set the cache on them for a year, while other resources will be set for an hour.

It will then take the response object and set a new header of Cache-Control to add a max-age value to the header.