Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware for static assets #2759

Open
predaytor opened this issue Nov 12, 2024 · 0 comments
Open

Middleware for static assets #2759

predaytor opened this issue Nov 12, 2024 · 0 comments

Comments

@predaytor
Copy link

Currently, the middleware in Fresh (2.0.0-alpha.25) does not have access to static assets, so we cannot modify the headers:

import { App } from 'fresh';
import { State } from '~/utils.ts';

export function speculationRules(app: App<State>) {
	app.use(async (ctx) => {
		const response = await ctx.next();
		response.headers.set('Speculation-Rules', '"/speculationrules.json"');
		return response;
	});

	app.get('/speculationrules.json', async (ctx) => {
		const response = await ctx.next();
		response.headers.set('Content-Type', 'application/speculationrules+json');
		response.headers.set('Access-Control-Allow-Origin', '*');
		return response;
	});
}

Workaround:

export function speculationRules(app: App<State>) {
	// ...

	app.get('/speculationrules.json', () => {
		const rules = `
			{
				"prerender": [
					{
						"source": "document",
						"where": { "href_matches": "/*" },
						"eagerness": "moderate"
					}
				],
				"prefetch": [
					{
						"where": { "not": { "href_matches": "/*" } },
						"eagerness": "moderate"
					}
				]
			}
		`;

		return new Response(rules, {
			headers: {
				'Content-Type': 'application/speculationrules+json',
				'Access-Control-Allow-Origin': '*',
			},
		});
	});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant