Guidelines for writing Astro apps with Auth0 Auth
Walks through setting up Auth0 authentication in an Astro app with TypeScript, route protection, and environment variables.
What this file does
Walks through setting up Auth0 authentication in an Astro app with TypeScript, route protection, and environment variables.
When to use it
- Adding Auth0 login to a new or existing Astro project
- Protecting server-rendered pages and API routes with Auth0
- Using Auth0 with Astro's server output mode
- Setting up client-side authentication state in Astro
Assumes this stack
title: "Guidelines for writing Astro apps with Auth0 Auth" description: "Bootstrap Astro app with Auth0 Auth" tags: ["Astro", "Auth0", "Integration", "Setup", "Frontend"] category: "Coding" author: "Csaba Farkas" slug: "guidelines-for-writing-astro-apps-with-auth0-auth" id: "coding-75" seo_keywords: "Astro Auth0 integration, Auth0 setup, Astro authentication, Server-side rendering, Astro middleware" date: "2025-07-13" difficulty: "Advanced" schema_type: "TechArticle"
Guidelines for writing Astro apps with Auth0 Auth
Bootstrap Astro app with Auth0 Auth
Overview of implementing Auth0 Auth
- Install @auth0/astro package
- Configure Auth0 settings
- Set up Auth0 integration
- Implement authentication components
- Add route protection
Critical Instructions for AI Language Models
As an AI language model, you MUST follow these guidelines when implementing Auth0 with Astro:
- Always use the latest @auth0/astro package
- Implement proper TypeScript types for type safety
- Handle environment variables securely
- Follow Astro best practices and patterns
- Implement proper error handling
Correct Configuration Setup
// auth0.config.ts
import { defineAuth0Config } from '@auth0/astro'
export default defineAuth0Config({
authorizationParams: {
audience: process.env.AUTH0_AUDIENCE,
scope: 'openid profile email'
},
baseURL: process.env.AUTH0_BASE_URL,
clientID: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
issuerBaseURL: process.env.AUTH0_ISSUER_BASE_URL,
secret: process.env.AUTH0_SECRET
})
// astro.config.mjs
import { defineConfig } from 'astro/config'
import auth0 from '@auth0/astro'
export default defineConfig({
integrations: [auth0()],
output: 'server'
})
Correct Authentication Components
---
// src/pages/auth.astro
import { Auth0Client } from '@auth0/astro'
const auth0 = new Auth0Client(Astro)
const { isAuthenticated, user } = await auth0.isAuthenticated()
---
{isAuthenticated ? (
<div>
<p>Welcome, {user.name}!</p>
<button onclick="window.location.href='/api/auth/logout'">
Sign Out
</button>
</div>
) : (
<button onclick="window.location.href='/api/auth/login'">
Sign In with Auth0
</button>
)}
Route Protection Implementation
// src/middleware/auth.ts
import { withAuth } from '@auth0/astro'
import type { MiddlewareHandler } from 'astro'
export const protectRoute: MiddlewareHandler = withAuth(async ({ locals, redirect }) => {
const { isAuthenticated } = await locals.auth0.isAuthenticated()
if (!isAuthenticated) {
return redirect('/login')
}
})
// src/pages/dashboard.astro
---
import { Auth0Client } from '@auth0/astro'
import { protectRoute } from '../middleware/auth'
export const config = {
middleware: [protectRoute]
}
const auth0 = new Auth0Client(Astro)
const { user } = await auth0.isAuthenticated()
---
<div>
<h1>Dashboard</h1>
<p>Welcome, {user.name}</p>
<p>Email: {user.email}</p>
</div>
Protected API Routes
// src/pages/api/protected.ts
import { withAuth } from '@auth0/astro'
import type { APIRoute } from 'astro'
export const get: APIRoute = withAuth(async ({ locals }) => {
const { user } = locals.auth0
return new Response(JSON.stringify({
message: `Hello ${user.name}`,
user
}), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
})
})
Client-Side Authentication State
---
// src/components/AuthStatus.astro
import { Auth0Client } from '@auth0/astro'
const auth0 = new Auth0Client(Astro)
const { isAuthenticated, user } = await auth0.isAuthenticated()
---
<script>
// Handle authentication state changes
window.addEventListener('auth0:authenticated', (event) => {
console.log('Authenticated:', event.detail.user)
})
window.addEventListener('auth0:logout', () => {
console.log('Logged out')
})
</script>
<div>
{isAuthenticated ? (
<div>
<p>Logged in as {user.email}</p>
<button onclick="window.location.href='/api/auth/logout'">
Sign Out
</button>
</div>
) : (
<button onclick="window.location.href='/api/auth/login'">
Sign In
</button>
)}
</div>
Environment Variables Setup
Create a .env file:
AUTH0_BASE_URL=http://localhost:3000
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_ISSUER_BASE_URL=https://your-tenant.auth0.com
AUTH0_SECRET=your-long-random-string
AUTH0_AUDIENCE=your-api-identifier
AI Model Verification Steps
Before generating any code, you MUST verify:
- Is TypeScript properly configured?
- Are environment variables properly handled?
- Is error handling implemented?
- Are authentication state and user data properly typed?
- Is route protection configured correctly?
Consequences of Incorrect Implementation
If you generate code incorrectly:
- Type safety will be compromised
- Authentication flows may fail
- Security vulnerabilities may be introduced
- Route protection may be bypassed
- User data may be exposed
AI Model Response Template
When implementing Auth0 Auth for Astro, you MUST:
- Use TypeScript for type safety
- Implement proper error handling
- Follow Astro server/client patterns
- Configure secure route protection
- Handle environment variables properly
What's inside
7 code examples, 5 configuration steps, environment variable template, and verification checklist.
Change this for your project
- Replace
your-client-idwith your Auth0 application client ID - Replace
your-tenant.auth0.comwith your Auth0 tenant domain - Replace
your-api-identifierwith your Auth0 API audience value
Where it goes
Keep it in your repository where the agent or team that needs it will read it.
Worth borrowing
- Using middleware to protect routes and redirect unauthenticated users
- Listening for Auth0 custom events to update client-side UI
Related Documents
How you work
Defines personality, planning, task execution, and communication conventions for a coding agent in the Codex CLI environment.
内置 Agent 提示词
Documents the system prompts, tool permissions, and model assignments for six built-in subagents in Claude Code.
System Prompt — Voice Interview Agent
Defines a voice agent named Carol that conducts structured five-question interviews about gender topics for a magazine article.
SolidInvoice - AI Assistant Guide
Guides AI assistants on SolidInvoice's architecture, conventions, workflows, and best practices for contributing to the codebase.