feat: enhance middleware to set speculation rules header

This commit is contained in:
ccbikai
2024-11-04 19:56:30 +08:00
parent affd4d2a9b
commit 0035b84e2c
2 changed files with 30 additions and 2 deletions

View File

@@ -1,4 +1,10 @@
export function onRequest(context, next) {
export async function onRequest(context, next) {
context.locals.SITE_URL = `${import.meta.env.SITE ?? ''}${import.meta.env.BASE_URL}`
return next()
const response = await next()
if (!response.bodyUsed) {
response.headers.set('Speculation-Rules', '"/rules/prefetch.json"')
}
return response
};

View File

@@ -0,0 +1,22 @@
export const prerender = false
export async function GET() {
return Response.json({
prerender: [
{
urls: ['/', '/tags'],
eagerness: 'eager',
},
],
prefetch: [
{
where: { href_matches: ['/posts/*'] },
eagerness: 'moderate',
},
],
}, {
headers: {
'Content-Type': 'application/speculationrules+json',
},
})
}