Skip to content

Commit

Permalink
Merge pull request #1174 from dpc-sdp/feature/no-cache-404
Browse files Browse the repository at this point in the history
fix(@dpc-sdp/nuxt-ripple): 🐛 [DDS-1878] Update default cache header rules for SDP sites
  • Loading branch information
dylankelly authored May 21, 2024
2 parents 0394d9a + 1c33736 commit 0cee303
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/nuxt-ripple/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { defineNuxtConfig } from 'nuxt/config'
import { createResolver } from '@nuxt/kit'

const { resolve } = createResolver(import.meta.url)
const assetCacheTime = 31536000 // 1 year

export default defineNuxtConfig({
runtimeConfig: {
Expand Down Expand Up @@ -47,9 +46,16 @@ export default defineNuxtConfig({
},
nitro: {
routeRules: {
'**': {
headers: {
// rendered html pages should be cached by the browser for 30s and by reverse proxies for 15min. Always revalidate
'cache-control': `public,max-age=30,s-maxage=900,must-revalidate`
}
},
'/_nuxt/**': {
headers: {
'cache-control': `public,max-age=${assetCacheTime},s-maxage=${assetCacheTime}`
// assets should be cached by the browser for a day and reverse proxies for a year
'cache-control': `public,max-age=86400,s-maxage=31536000`
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions packages/nuxt-ripple/server/plugins/cache-control.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { NitroApp } from 'nitropack'

// fix type stub - See https://github.com/nuxt/nuxt/issues/18556
export type NitroAppPlugin = (nitro: NitroApp) => void
function defineNitroPlugin(def: NitroAppPlugin): NitroAppPlugin {
return def
}

export default defineNitroPlugin(async (NitroApp) => {
NitroApp.hooks.hook('error', (error, { event }) => {
if (event && (error as any).statusCode === 404) {
// 404 responses are cached for 5s by reverse proxy to avoid load on origin, browsers should not cache
setHeader(
event,
'cache-control',
'public, proxy-revalidate, s-maxage=5, max-age=0'
)
}
if (event && (error as any).statusCode === 500) {
// 500 errors should never be cached
setHeader(event, 'cache-control', 'no-cache, private, max-age=0')
}
})
})

0 comments on commit 0cee303

Please sign in to comment.