#auth question

3 messages · Page 1 of 1 (latest)

tight veldtBOT
#

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

#

You can use Astro Middleware to implement authentication with a token. Middleware allows you to intercept requests and responses and inject behaviors dynamically. You can also mutate a locals object that is available in all Astro components and API endpoints.

Here's an example of an authentication middleware:

// src/middleware.ts
export async function onRequest({ cookies, locals }, next) {
  // Check for the "sid" user session ID cookie.
  // Return a 405 (Not Allowed) if the cookie is missing.
  const sessionId = cookies.get("sid");
  if (!sessionId) {
    return new Response(null, {status: 405});
  }
  // Use your own `getUser()` function to validate the user.
  // Return a 405 (Not Allowed) if the user isn't real.
  const user = await getUser(sessionId);
  if (!user) {
    return new Response(null, {status: 405});
  }
  // Attach the loaded user to the `locals` object.
  // Now, it can be read in the page route!
  locals.user = user;
  // Return `next()` to return the response.
  return next();
}

You can then access the user object in your Astro components:

---
// src/pages/index.astro
const { user } = Astro.locals
---

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

Using middleware for authentication is a cleaner and more efficient approach compared to checking the cookie in each page that needs it.

For more information on Middleware, refer to the Astro 2.6 blog post (https://astro.build/blog/astro-260) and the Middleware documentation guide (https://docs.astro.build/en/guides/middleware).

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

Astro

A handful of experimental features go stable in Astro 2.6 including middleware, hybrid SSR output mode, custom client directives, and CSS inlining. Experimental support for a new redirects API is also introduced.

#

@maiden cedar kapa.ai is still learning and improving, please let us how it did by reacting below