Skip to content

Commit 75d1bf2

Browse files
authored
perf: use spa fallback on cold cache (#878)
1 parent 338b86a commit 75d1bf2

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

app/plugins/fix.client.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export default defineNuxtPlugin({
2+
enforce: 'pre',
3+
setup(nuxtApp) {
4+
// TODO: investigate why this is needed
5+
nuxtApp.payload.data ||= {}
6+
},
7+
})

modules/isr-fallback.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { readFileSync, writeFileSync } from 'node:fs'
2+
import { resolve } from 'node:path'
3+
import { defineNuxtModule } from 'nuxt/kit'
4+
import { provider } from 'std-env'
5+
6+
export default defineNuxtModule({
7+
meta: {
8+
name: 'isr-fallback',
9+
},
10+
setup(_, nuxt) {
11+
if (provider !== 'vercel') {
12+
return
13+
}
14+
15+
nuxt.hook('nitro:init', nitro => {
16+
nitro.hooks.hook('compiled', () => {
17+
const spaTemplate = readFileSync(nitro.options.output.publicDir + '/200.html', 'utf-8')
18+
for (const path of ['package', '']) {
19+
const outputPath = resolve(
20+
nitro.options.output.serverDir,
21+
'..',
22+
path,
23+
'spa.prerender-fallback.html',
24+
)
25+
writeFileSync(outputPath, spaTemplate)
26+
}
27+
})
28+
})
29+
},
30+
})

nuxt.config.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export default defineNuxtConfig({
5959
app: {
6060
head: {
6161
htmlAttrs: { lang: 'en-US' },
62+
title: 'npmx',
6263
link: [
6364
{
6465
rel: 'search',
@@ -85,8 +86,10 @@ export default defineNuxtConfig({
8586
routeRules: {
8687
'/': { prerender: true },
8788
'/opensearch.xml': { isr: true },
88-
'/**': { isr: 60 },
89-
'/package/**': { isr: 60 },
89+
'/**': { isr: getISRConfig(60, true) },
90+
'/api/**': { isr: 60 },
91+
'/200.html': { prerender: true },
92+
'/package/**': { isr: getISRConfig(60, true) },
9093
'/:pkg/.well-known/skills/**': { isr: 3600 },
9194
'/:scope/:pkg/.well-known/skills/**': { isr: 3600 },
9295
// never cache
@@ -279,3 +282,15 @@ export default defineNuxtConfig({
279282
dirs: ['~/composables', '~/composables/*/*.ts'],
280283
},
281284
})
285+
286+
function getISRConfig(expirationSeconds: number, fallback = false) {
287+
if (fallback) {
288+
return {
289+
expiration: expirationSeconds,
290+
fallback: 'spa.prerender-fallback.html',
291+
} as { expiration: number }
292+
}
293+
return {
294+
expiration: expirationSeconds,
295+
}
296+
}

0 commit comments

Comments
 (0)