DEV Community

Cover image for Building an AI Therapy App with Next.js, Better Auth, and Railway
Vivek
Vivek Subscriber

Posted on

Building an AI Therapy App with Next.js, Better Auth, and Railway

Building an AI Therapy App with Next.js, Better Auth, and Railway

I just launched my submission for the Railway hackathon - a Next.js Better Auth + AI Template that combines modern authentication with AI-powered features. Here's how I built it and why Railway was the perfect platform for deployment.

๐Ÿš€ What I Built

Deploy on Railway

My template includes:

  • Complete authentication system with Better Auth
  • PostgreSQL database with Drizzle ORM
  • AI therapy app demo with 6 specialized therapists
  • HeyGen streaming avatars for lifelike conversations
  • Real-time chat powered by OpenRouter
  • Modern UI with Tailwind CSS and Radix UI

๐ŸŽฏ The Problem I Solved

Building authentication from scratch is tedious. Adding AI features makes it even more complex. I wanted to create a production-ready foundation that developers could:

  1. Deploy in one click and have working auth immediately
  2. See real AI implementation with streaming avatars
  3. Learn modern patterns for full-stack development
  4. Customize easily for their own projects

๐Ÿ› ๏ธ Tech Stack Choices

Why Next.js 15?

  • App Router for modern React patterns
  • Turbopack for lightning-fast development
  • Server Actions for seamless client-server communication
  • Built-in optimization for production deployment

Why Better Auth over NextAuth?

// Cleaner, more performant, better DX
import { betterAuth } from "better-auth"

export const auth = betterAuth({
  database: db,
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: true,
  },
  // Much simpler configuration!
})
Enter fullscreen mode Exit fullscreen mode

Why Railway?

  • Zero-config PostgreSQL - Database provisioned automatically
  • Environment management - Secure variable handling
  • One-click deployment - Perfect for templates
  • Cost-effective scaling - Pay only for usage

๐Ÿค– AI Features Implementation

The standout feature is the InnerLink AI therapy demo. Here's how I built it:

1. HeyGen Streaming Avatars

import { StreamingAvatar } from '@heygen/streaming-avatar'

const avatar = new StreamingAvatar({
  apiKey: process.env.HEYGEN_API_KEY,
  avatarId: selectedTherapist.id
})

// Real-time avatar streaming with voice
await avatar.speak(responseText)
Enter fullscreen mode Exit fullscreen mode

2. AI Conversation System

// Custom prompts for each therapist specialty
export function getTherapySystemPrompt(sessionData: SessionData) {
  return `You are ${selectedAvatar.name}, a warm and experienced therapist 
    specializing in ${selectedAvatar.specialty}. 

    CLIENT: Feeling ${currentMood}, focusing on ${sessionFocus}

    Provide a focused 3-minute therapy session...`
}
Enter fullscreen mode Exit fullscreen mode

3. Multiple AI Therapists

I created 6 specialized therapists:

  • Elenora - Cognitive Behavioral Therapy
  • Judy - Mindfulness & Meditation
  • June - Workplace Wellness
  • Silas - Anxiety & Stress Management
  • Bryan - Professional Support
  • Wayne - Life Coaching & Goals

๐Ÿ—๏ธ Architecture Decisions

Database Schema

// Clean, extensible user schema
export const user = pgTable("user", {
  id: text("id").primaryKey(),
  name: text("name").default(""),
  email: text("email").notNull().unique(),
  emailVerified: boolean("emailVerified").notNull().default(false),
  image: text("image"),
  createdAt: timestamp("createdAt").defaultNow(),
  updatedAt: timestamp("updatedAt").defaultNow().$onUpdate(() => new Date()),
})
Enter fullscreen mode Exit fullscreen mode

Session Management

// Secure session handling with Better Auth
export const session = pgTable("session", {
  id: text("id").primaryKey(),
  userId: text("userId").notNull().references(() => user.id),
  expiresAt: timestamp("expiresAt").notNull(),
  token: text("token").notNull().unique(),
  ipAddress: text("ipAddress"),
  userAgent: text("userAgent"),
})
Enter fullscreen mode Exit fullscreen mode

๐ŸŽจ UI/UX Design Philosophy

I focused on modern, accessible design:

Component System

// Consistent, reusable components with Radix UI
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"

// Dark mode support built-in
const ThemeProvider = ({ children }) => (
  <NextThemesProvider attribute="class" defaultTheme="system">
    {children}
  </NextThemesProvider>
)
Enter fullscreen mode Exit fullscreen mode

Responsive Design

  • Mobile-first approach with Tailwind CSS
  • Touch-friendly interfaces for therapy sessions
  • Accessibility considerations throughout

๐Ÿš€ Railway Integration

Railway made deployment incredibly smooth:

1. Database Setup

# Railway automatically provisions PostgreSQL
services:
  - name: database
    type: postgresql
    variables:
      POSTGRES_DB: innerlink
      POSTGRES_USER: ${{ POSTGRES_USER }}
      POSTGRES_PASSWORD: ${{ POSTGRES_PASSWORD }}
Enter fullscreen mode Exit fullscreen mode

2. Environment Variables

Railway's variable management handles:

  • Database connection strings
  • API keys for external services
  • Authentication secrets
  • Public URLs for callbacks

3. Automatic Deployments

Connected to GitHub for:

  • Push-to-deploy workflow
  • Preview deployments for pull requests
  • Rollback capabilities for production

๐Ÿ“ˆ Performance Optimizations

Database Queries

// Optimized queries with Drizzle ORM
const users = await db.select({
  id: user.id,
  name: user.name,
  email: user.email,
}).from(user).where(eq(user.emailVerified, true))
Enter fullscreen mode Exit fullscreen mode

Streaming Responses

// Real-time AI responses
export async function POST(request: Request) {
  const stream = await openrouter.chat.completions.create({
    model: "openai/gpt-4",
    messages: conversationHistory,
    stream: true,
  })

  return new StreamingTextResponse(stream)
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Security Implementation

Authentication Security

  • Email verification required for all accounts
  • Secure session tokens with HTTP-only cookies
  • CSRF protection built into Better Auth
  • Rate limiting on authentication endpoints

Database Security

  • Connection encryption with SSL
  • Environment-based secrets (never committed to git)
  • User input validation with Zod schemas

๐Ÿ“Š Results & Impact

This template provides:

โšก Developer Experience

  • 5-minute setup from clone to running app
  • Type safety throughout the entire stack
  • Hot reload with Turbopack development
  • Clear documentation and examples

๐Ÿข Production Ready

  • Scalable architecture on Railway platform
  • Security best practices implemented
  • Performance optimized for real-world usage
  • Monitoring ready with built-in logging

๐Ÿค– AI Innovation

  • Real streaming avatars for engaging UX
  • Multiple AI providers for flexibility
  • Conversation memory and context handling
  • Customizable personalities for different use cases

๐ŸŽฏ Use Cases

This template is perfect for:

AI-Powered Apps

  • Mental health platforms
  • Educational assistants
  • Customer support bots
  • Virtual coaching apps

SaaS Platforms

  • User dashboards
  • Subscription management
  • Team collaboration tools
  • Analytics platforms

Learning Projects

  • Modern React patterns
  • Authentication implementation
  • AI integration strategies
  • Full-stack development

๐Ÿ”ฎ Future Enhancements

I'm planning to add:

  • OAuth providers (Google, GitHub, Discord)
  • Multi-tenant support for SaaS applications
  • Advanced AI features like voice recognition
  • Analytics dashboard for user insights
  • Mobile app with React Native

๐Ÿค Community Impact

Open Source Benefits

  • MIT License for maximum flexibility
  • Clear documentation for easy contribution
  • Modular architecture for easy customization
  • Best practices for community learning

Educational Value

  • Real-world patterns for authentication
  • AI integration examples with actual APIs
  • Modern tooling and development practices
  • Production deployment strategies

๐Ÿ† Why This Deserves to Win

This template represents the future of web development:

  1. Innovation - Combines traditional auth with cutting-edge AI
  2. Practicality - Solves real developer pain points
  3. Quality - Production-ready code with best practices
  4. Community - Open source and educational value
  5. Railway Integration - Showcases platform capabilities perfectly

๐Ÿš€ Try It Now!

Deploy on Railway

GitHub Repository: github.com/vivekvt/innerlink

Live Demo: InnerLink


What's Next?

I'd love to hear your feedback! Try the template, build something amazing, and let me know how it works for your use case.

Questions? Drop them in the comments below!

This project was built for the Railway hackathon. Railway's platform made deployment incredibly smooth, and I'm excited to see how the community uses this template to build the next generation of AI-powered applications.

Top comments (0)