Guidelines for writing Angular apps with Better Auth
Guides AI models to scaffold an Angular app with Better Auth, covering config, components, route guards, and env vars.
What this file does
Guides AI models to scaffold an Angular app with Better Auth, covering config, components, route guards, and env vars.
When to use it
- Starting a new Angular project that needs Better Auth authentication
- Adding Better Auth to an existing Angular app with route protection
- Teaching an AI model to generate Angular auth code consistently
- Reviewing a Better Auth integration for security and type safety
Assumes this stack
title: "Guidelines for writing Angular apps with Better Auth" description: "Bootstrap Angular app with Better Auth" tags: ["Angular", "Better Auth", "Integration", "Setup", "Frontend"] category: "Coding" author: "Csaba Farkas" slug: "guidelines-for-writing-angular-apps-with-better-auth" id: "coding-82" seo_keywords: "Angular Better Auth integration, Better Auth setup, Angular authentication, Route protection, Angular services" date: "2025-07-13" difficulty: "Advanced" schema_type: "TechArticle"
Guidelines for writing Angular apps with Better Auth
Bootstrap Angular app with Better Auth
Overview of implementing Better Auth
- Install better-auth package
- Configure auth instance
- Set up Angular module 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 Better Auth with Angular:
- Always use the latest better-auth package
- Implement proper TypeScript types for type safety
- Handle environment variables securely
- Follow Angular best practices and patterns
- Implement proper error handling
Correct Auth Configuration
// auth.config.ts
import { betterAuth } from 'better-auth';
import { Pool } from 'pg';
import { environment } from './environments/environment';
export const auth = betterAuth({
database: new Pool({
connectionString: environment.databaseUrl,
ssl: environment.production
}),
emailAndPassword: {
enabled: true,
requireEmailVerification: true
},
session: {
expiresIn: '7d'
}
});
Correct Module Setup
// app.module.ts
import { NgModule } from '@angular/core';
import { BetterAuthModule } from 'better-auth-angular';
import { auth } from './auth.config';
@NgModule({
imports: [
BetterAuthModule.forRoot(auth, {
persistSession: true,
autoRefresh: true
})
]
})
export class AppModule { }
Correct Authentication Components
// auth.component.ts
import { Component, inject } from '@angular/core';
import { BetterAuthService } from 'better-auth-angular';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-auth',
template: `
<ng-container *ngIf="auth.isAuthenticated$ | async; else loginForm">
<div *ngIf="auth.user$ | async as user">
<p>Welcome, {{ user.email }}</p>
<button (click)="logout()">Sign Out</button>
</div>
</ng-container>
<ng-template #loginForm>
<form [formGroup]="form" (ngSubmit)="login()">
<input formControlName="email" type="email" placeholder="Email" />
<input formControlName="password" type="password" placeholder="Password" />
<button type="submit" [disabled]="form.invalid">Sign In</button>
</form>
</ng-template>
`
})
export class AuthComponent {
private auth = inject(BetterAuthService);
private fb = inject(FormBuilder);
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]]
});
async login() {
if (this.form.valid) {
try {
const { email, password } = this.form.value;
await this.auth.login(email!, password!);
} catch (error) {
console.error('Authentication failed:', error);
}
}
}
async logout() {
try {
await this.auth.logout();
} catch (error) {
console.error('Logout failed:', error);
}
}
}
Route Protection Implementation
// auth.guard.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BetterAuthService } from 'better-auth-angular';
import { map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthGuard {
constructor(private auth: BetterAuthService, private router: Router) {}
canActivate() {
return this.auth.isAuthenticated$.pipe(
tap(isAuthenticated => {
if (!isAuthenticated) {
this.router.navigate(['/login']);
}
})
);
}
}
// app.routes.ts
import { Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
export const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
}
];
Environment Variables Setup
Create an environment.ts file:
export const environment = {
production: false,
databaseUrl: 'postgresql://user:password@localhost:5432/mydb',
authSecret: 'your-secret-key'
};
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 Better Auth for Angular, you MUST:
- Use TypeScript for type safety
- Implement proper error handling
- Follow Angular dependency injection patterns
- Configure secure route protection
- Handle environment variables properly
What's inside
6 code examples, 5 critical instructions, 5 verification steps, and a response template
Change this for your project
- Replace
'postgresql://user:password@localhost:5432/mydb'with your actual database URL - Replace
'your-secret-key'with a real secret key for auth - Replace
'7d'with your preferred session expiry duration
Where it goes
Keep it in your repository where the agent or team that needs it will read it.
Worth borrowing
- Using an injectable AuthGuard with RxJS pipe to redirect unauthenticated users
- Separating auth config into its own file and importing it into the module
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.