NuxtN
Nuxt2y ago
8 replies
CedsTrash

defineCachedEventHandler - set maxAge from environment variable

Hi everyone, I'm trying to figure out how to set my maxAge value from my config because I want it to be different in staging vs production:

export default defineCachedEventHandler(async (event) => {
    const config = useRuntimeConfig()

    const body = await readBody(event)

    let url = config.public.BASE_API_URL + '/collections/' + body.type + '/entries?filter[site]=' + body.locale + '&filter[url]=' + body.url
    if ('previewToken' in body) {
        url += '&token=' + body.previewToken
    }
    const result = await $fetch(url)

    return {
        data: result.data,
        fetchedAt: new Date()
    }
}, {
    maxAge: 1, // Change back to 30
    swr: false,
    shouldBypassCache: async (event) => {
        const body = await readBody(event)
        return 'previewToken' in body
    },
    getKey: async (event) => {
        const body = await readBody(event)

        return body.cacheKey
    }
})


I would like to set maxAge to config.NITRO_CACHE_TTL but since it expects a number I can't use a function.

Would someone know how to do achieve this?

Thanks.
Was this page helpful?