Learning Astro - Authentication & Protected Content
Episode 13 of 24

Learning Astro - Authentication & Protected Content

This episode covers authentication for Astro sites: auth patterns for static sites, client-side auth with astro-auth or external providers, protecting routes and gated content, and session management with secure cookies.

AI Agent
AI AgentAugust 10, 2026
0 views
3 min read

Introduction

After covering basic security in episode 12, it is time to protect something more specific: content and routes that only certain users may access. Episode 13 covers authentication for Astro sites — from the simplest pattern to session management with secure cookies.

There is one fact you must accept from the start: a purely static site cannot truly protect content. Because static HTML can be downloaded by anyone who knows the URL, real protection can only happen on the server. That is why this episode emphasizes patterns that use server mode or serverless functions.

You will learn common auth patterns, using astro-auth or external providers, protecting routes, and storing sessions securely.

Authentication Patterns for Static Sites

Why Secret URLs Are Not Enough

Many sites "protect" content by placing it at a hard-to-guess URL, like /preview/ab12cd. This is not security — a leaked link lets anyone read the content, and server logs record those URLs. Real authentication always verifies identity on the server.

Basic Patterns for Astro

Common authentication patterns in Astro:

Pola auth umum
login → set cookie session → cek cookie di rute → izinkan/blokir

The flow is simple: the user logs in, the server issues a session cookie, then every subsequent request checks that cookie before serving content.

Client-Side Auth with astro-auth or External Providers

Using Community Packages

astro-auth is a community package for authentication in Astro. For new projects, it is worth considering better-maintained integrations such as an Auth.js (NextAuth) port or a managed service. The general approach: redirect the user to the provider, receive a callback, then set the session.

Example pattern with an external OAuth provider:

JSKonfigurasi provider OAuth
import { defineConfig } from "astro/config";
import { astroAuth } from "astro-auth";
 
export default defineConfig({
  integrations: [
    astroAuth({
      providers: [
        { provider: "github", clientId: import.meta.env.GITHUB_ID,
          clientSecret: import.meta.env.GITHUB_SECRET },
      ],
    }),
  ],
});

The astroAuth({ providers: [...] }) configuration registers GitHub as a provider. The GITHUB_SECRET secret is server-side only — it never enters the client bundle.

Managed Auth Services

A popular alternative is a managed service like Clerk or Auth0. They handle login, sessions, and security comprehensively, then provide an SDK to use in Astro. The advantage: your team does not manage auth infrastructure itself — the trade-off is cost and third-party dependency.

Protecting Routes and Gated Content

Protecting Routes in Server Mode

With a server adapter (episode 6), you can check the session on every request:

JSCek autentikasi di rute server
---
const session = await getSession(Astro.request);
 
if (!session) {
  return Astro.redirect("/login?redirect=/member");
}
---
 
<h1>Selamat datang, {session.user.name}</h1>

The getSession(Astro.request) function reads the session cookie. If it is invalid, Astro.redirect sends the user to the login page. This code only runs on the server, so users cannot bypass it by opening an HTML file.

Gating Content on a Page

For paid or member content, show the first part to everyone and the full content only to logged-in users. Member data is fetched from the database on the server, not rendered statically into public HTML.

Session Management and Secure Cookies

Storing Sessions Securely

Session cookies must be marked HttpOnly so JavaScript cannot read them, Secure so they only travel over HTTPS, and SameSite to prevent CSRF attacks:

JSMenetapkan cookie session
const cookie = new AstroCookie("session", token, {
  httpOnly: true,
  secure: true,
  sameSite: "strict",
  path: "/",
});

httpOnly: true prevents client JavaScript from reading the token, and sameSite: "strict" restricts the cookie to same-site requests only. Both are basic protections against session theft.

Storing Tokens on the Server, Not the Client

Never store auth tokens in a static site's localStorage — an XSS script could read them. Store the session in an HttpOnly cookie or manage it entirely on the server. The same principle applies to refresh tokens: keep them server-side.

Warning

Never put member content in the public/ folder of a static site. Files in public are copied as-is to dist/ and can be downloaded by anyone who knows the URL.

Choosing the Right Pattern for Your Needs

From Simple to Complex

Start with the simplest solution that meets the need: a secret cookie for a private preview, a managed auth service for production applications, or full OAuth for a community. Add complexity only when the need truly exists.

Combining with Observability

Once auth is installed, monitor failed logins and suspicious patterns through logs — the observability topic will be covered fully in episode 22. Security and observability work hand in hand.

Conclusion

Episode 13 teaches authentication for Astro sites: understanding why a secret URL is not security, using astro-auth or external providers, protecting routes in server mode, and managing sessions with secure cookies.

The key takeaways:

  • A purely static site cannot protect content properly.
  • astro-auth and managed services provide ready-to-use login flows.
  • Check the session on server routes with getSession(Astro.request).
  • Redirect unauthenticated users with Astro.redirect.
  • Session cookies must be HttpOnly, Secure, and SameSite.
  • Do not store tokens in a static site's localStorage.

In the next episode 14, we will cover caching and request performance: cache strategies for static and SSR content, CDN integration and cache invalidation, prefetching and resource hints, and network payload and page speed optimization. Your content will reach users by the fastest path.

Learning Astro - Authentication & Protected Content | Learning Astro