#How to redirect in the middleware?

4 messages · Page 1 of 1 (latest)

vivid hinge
#

Have this code in middleware.ts

import { defineMiddleware } from "astro/middleware";

export const onRequest = defineMiddleware((context, next) => {
  if (context.url.pathname.includes("sign-in")) {
    return next(new Request("/dashboard"));
  }

  return next();
});

Getting an error that says
Failed to parse URL from /dashboard

normal streamBOT
#

Hi @vivid hinge. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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.


#

Summary:

  • Use context.redirect("/dashboard") to redirect the user.
  • Use context.rewrite("/dashboard") to rewrite the content without changing the URL.
  • Do not use new Request("/dashboard") with a relative path; it must be an absolute URL if you use the Request constructor Middleware Guide: Rewriting.

Let me know if you need an example for a specific use case!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: