Your error, “Failed to parse URL from /dashboard”, occurs because the Request constructor expects an absolute URL, not a relative path, when used in middleware. In Astro middleware, if you want to rewrite or redirect, you have two main options:
1. Redirect (change the browser’s URL)
To perform a redirect (change the URL in the browser), use context.redirect():
import { defineMiddleware } from "astro:middleware";
export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname.includes("sign-in")) {
return context.redirect("/dashboard");
}
return next();
});
This will send a proper HTTP redirect response to the client, and is the recommended way to send users to a new page in most cases Astro redirect() API.
2. Rewrite (show different content, keep the URL)
If you want to show the content of /dashboard while keeping the original URL in the browser, use context.rewrite():
import { defineMiddleware } from "astro:middleware";
export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname.includes("sign-in")) {
return context.rewrite("/dashboard");
}
return next();
});
This will serve the content of /dashboard at the current URL, without changing the browser’s address bar Astro rewrite() API.
Note: If you want to use the Request constructor, you must provide an absolute URL, e.g. new Request(new URL("/dashboard", context.url)), but for most use cases, passing a string path to context.rewrite() or context.redirect() is simpler and recommended.