#Intercepting requests with middleware

3 messages · Page 1 of 1 (latest)

frail steppe
#

Can I use Astro Middleware to intercept any client side requests?

delicate plazaBOT
#

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

#

Astro Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. However, it doesn't directly intercept client-side requests. Middleware is available in both SSG and SSR Astro projects (source (https://docs.astro.build/en/guides/middleware)).

Here's an example of using Astro Middleware for authentication:

export async function onRequest({ cookies, locals }, next) => {
  const sessionId = cookies.get("sid");
  if (!sessionId) {
    return new Response(null, {status: 405});
  }
  const user = await getUser(sessionId);
  if (!user) {
    return new Response(null, {status: 405});
  }
  locals.user = user;
  return next();
}

And then accessing the locals.user object in an Astro component:

---
const { user } = Astro.locals
---

<h1>Hello {user.name}!</h1>

(source (https://astro.build/blog/astro-260))

For intercepting client-side requests, you might need to use a different approach or tool, as Astro Middleware is focused on server-side request handling.

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