Salta ai contenuti

Authentication

Questi contenuti non sono ancora disponibili nella tua lingua.

Authentication and authorization are two security processes that manage access to your website or app. Authentication verifies a visitor’s identity, while authorization grants access to protected areas and resources.

Authentication allows you to customize areas of your site for logged-in individuals and provides the greatest protection for personal or private information. Authentication libraries (e.g. Better Auth, Clerk) provide utilities for multiple authentication methods such as email sign-in and OAuth providers.

See how to add authentication with Supabase, add authentication with Firebase, or add authentication with Scalekit in our dedicated guides for these backend services.

Better Auth is a framework-agnostic authentication (and authorization) framework for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities.

It supports Astro out of the box, and you can use it to add authentication to your Astro project.

Terminal window
npm install better-auth

For detailed setup instructions, check out the Better Auth Installation Guide.

Configure your database table to store user data and your preferred authentication methods as described in the Better Auth Installation Guide. Then, you’ll need to mount the Better Auth handler in your Astro project.

src/pages/api/auth/[...all].ts
import { auth } from "../../../lib/auth"; // import your Better Auth instance
import type { APIRoute } from "astro";
export const prerender = false; // Not needed in 'server' mode
export const ALL: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};

Follow the Better Auth Astro Guide to learn more.

Better Auth offers a createAuthClient() helper for various frameworks, including Vanilla JS, React, Vue, Svelte, and Solid.

For example, to create a client for React, import the helper from 'better-auth/react':

src/lib/auth-client.ts
import { createAuthClient } from 'better-auth/react';
export const authClient = createAuthClient();
export const { signIn, signOut } = authClient;

Once your client is set up, you can use it to authenticate users in your Astro components or any framework-specific files. The following example adds the ability to log in or log out with your configured signIn() and signOut() functions.

src/pages/index.astro
---
import Layout from "../layouts/Base.astro";
---
<Layout>
<button id="login">Login</button>
<button id="logout">Logout</button>
<script>
const { signIn, signOut } = await import("../lib/auth-client");
const loginButton = document.querySelector<HTMLButtonElement>("#login");
const logoutButton = document.querySelector<HTMLButtonElement>("#logout");
if (!loginButton || !logoutButton) throw new Error("Buttons not found");
loginButton.onclick = () =>
signIn.social({
provider: "github",
callbackURL: "/dashboard",
});
logoutButton.onclick = () => signOut();
</script>
</Layout>

You can then use the auth object to get the user’s session data in your server-side code. The following example personalizes page content by displaying an authenticated user’s name:

src/pages/index.astro
---
import { auth } from "../lib/auth"; // import your Better Auth instance
export const prerender = false; // Not needed in 'server' mode
const session = await auth.api.getSession({
headers: Astro.request.headers,
});
---
<p>{session.user?.name}</p>

You can also use the auth object to protect your routes. The following example uses Astro’s advanced routing with Hono to require an authenticated session for every route under /dashboard, redirecting to the home page otherwise:

src/fetch.ts
import { Hono, type Context, type Next } from "hono";
import { astro } from "astro/hono";
import { auth } from "./lib/auth"; // import your Better Auth instance
const app = new Hono();
// Protect every route under /dashboard.
app.use("/dashboard", requireAuth);
app.use("/dashboard/*", requireAuth);
// Run Astro's built-in pipeline for all other requests.
app.use(astro());
export default app;
async function requireAuth(c: Context, next: Next) {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
});
if (!session) {
return c.redirect("/");
}
return next();
}

Clerk is a complete suite of embeddable UIs, flexible APIs, and admin dashboards to authenticate and manage your users. An official Clerk SDK for Astro is available.

Install @clerk/astro using the package manager of your choice.

Terminal window
npm install @clerk/astro

Follow Clerk’s own Astro Quickstart guide to set up Clerk integration and middleware in your Astro project.

Clerk provides components that allow you to control the visibility of pages based on your user’s authentication state. Show logged out users a sign in button instead of the content available to users who are logged in:

src/pages/index.astro
---
import Layout from "../layouts/Base.astro";
import { Show, UserButton, SignInButton } from "@clerk/astro/components";
export const prerender = false; // Not needed in 'server' mode
---
<Layout>
<Show when="signed-in">
<UserButton />
</Show>
<Show when="signed-out">
<SignInButton />
</Show>
</Layout>

Clerk also allows you to protect routes on the server using middleware:

  1. Set clerkMiddleware() as the onRequest handler in your middleware:

    src/middleware.ts
    import { clerkMiddleware } from "@clerk/astro/server";
    export const onRequest = clerkMiddleware({
    /* options */
    });
  2. Access the authentication state in your pages and API routes with locals.auth(). This allows you to check if a user is authenticated and take appropriate actions (e.g. redirecting to the sign-in page or returning a different response).

    src/pages/dashboard.astro
    ---
    const { isAuthenticated, redirectToSignIn } = Astro.locals.auth();
    if (!isAuthenticated) return redirectToSignIn();
    ---
    <h1>Dashboard</h1>

Lucia is a resource for implementing session-based authentication in a number of frameworks, including Astro.

  1. Create a basic sessions API with your chosen database.
  2. Add session cookies using endpoints and middleware.
  3. Implement GitHub OAuth using the APIs you implemented.

Scalekit is an authentication platform for B2B and AI applications. It manages the full OAuth 2.0 and OIDC flow, supporting methods such as social login, enterprise SSO, and magic links. It then returns tokens and a user profile without requiring a custom login UI.

A single Scalekit environment can support multiple applications. This allows you to authenticate once and share the same session across all your properties (e.g. app.yourcompany.com and docs.yourcompany.com).

Follow the Scalekit & Astro guide to add authentication to your Astro SSR project using social login, enterprise SSO, and more.

Contribuisci Comunità Sponsor