#trigger api get endpoint to every route before send html
1 messages · Page 1 of 1 (latest)
To intercept requests and responses before a page or endpoint is rendered in Astro, you can use the onRequest() middleware function. This function is exported from src/middleware.js and is called before rendering every page or API route.
Here is an example of how you might use it:
export function onRequest (context, next) {
// intercept response data from a request
// optionally, transform the response
// return a Response directly, or the result of calling `next()`
return next();
};
You can also use the sequence() function to execute multiple middleware functions in the order they are passed. Here's an example:
import { sequence } from "astro:middleware";
async function validation(_, next) {...}
async function auth(_, next) {...}
async function greeting(_, next) {...}
export const onRequest = sequence(validation, auth, greeting);
Remember, the onRequest() function must return a Response, either directly or by calling next().