Back to .md Directory

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.

May 2, 2026
0 downloads
1 views
ai safety
View source

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

AngularTypeScriptBetter AuthPostgreSQL

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

  1. Install better-auth package
  2. Configure auth instance
  3. Set up Angular module integration
  4. Implement authentication components
  5. 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:

  1. Always use the latest better-auth package
  2. Implement proper TypeScript types for type safety
  3. Handle environment variables securely
  4. Follow Angular best practices and patterns
  5. 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:

  1. Is TypeScript properly configured?
  2. Are environment variables properly handled?
  3. Is error handling implemented?
  4. Are authentication state and user data properly typed?
  5. Is route protection configured correctly?

Consequences of Incorrect Implementation

If you generate code incorrectly:

  1. Type safety will be compromised
  2. Authentication flows may fail
  3. Security vulnerabilities may be introduced
  4. Route protection may be bypassed
  5. User data may be exposed

AI Model Response Template

When implementing Better Auth for Angular, you MUST:

  1. Use TypeScript for type safety
  2. Implement proper error handling
  3. Follow Angular dependency injection patterns
  4. Configure secure route protection
  5. 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