DEV Community

Cover image for MedHack - your health companion
Agastya Khati
Agastya Khati

Posted on

MedHack - your health companion

Auth0 for AI Agents Challenge Submission

This is a submission for the Auth0 for AI Agents Challenge

What I Built

MedHack is an AI-powered health assistance platform designed to make basic medical guidance and personalized nutrition planning accessible to everyone—especially in environments where professional healthcare is difficult to reach, expensive, or confusing to navigate.

The application has two core AI agents:

MedScan Diagnostic Agent
This agent analyzes medical images such as X-rays, CT scans, MRIs, and even photos of skin rashes or visible injuries. It helps users understand what might be happening in their body before they reach a doctor.
It does not replace medical professionals—it simply provides early clarity, reduces anxiety, and helps users ask better questions when they do seek treatment.

Diet Planner Agent
Instead of generating generic diet charts, this agent works interactively.
It asks about age, activity, preferences, medical conditions, routine, and even budget.
Then it produces a personalized weekly meal plan with calorie targets, macronutrient breakdowns, grocery list, and ongoing chat-based adjustments.
The structured plan can then be downloaded as a PDF or emailed directly to the user.

Demo

Live Demo: https://med-hack.vercel.app/
Github Repo : https://github.com/kris70lesgo/Medhack

Watch the video for the live demonstration of medhack

Quick Overview

1) Landing Page / Home Section
AI-powered personal health assistant combining diagnosis + nutrition planning

2) MedScan
User uploads an X-ray, skin image, or medical report for analysis.

3) Diet Planner
User provides age, weight, dietary preferences, medical conditions, and goals.

Smart Dialogue Screen
Agent asks clarifying questions to tailor the plan precisely.

7-Day Diet Plan Preview
A complete, structured 7-day meal plan is generated instantly

PDF Download
Plan can be securely downloaded as a formatted PDF

Email integration
The final plan is also delivered via email for convenience

Auth0 Roles and actions
Role-based access differentiates free and premium feature access.
Automated role assignment ensures smooth and secure onboarding

Problem

Healthcare guidance today is fragmented and inefficient:

  • People rely on Google searching symptoms, which often leads to confusion and anxiety.
  • Diet plans online are generic, not personalized to health conditions, goals, or daily routines.
  • Consulting doctors or nutritionists is expensive and often requires waiting time.
  • Medical reports, scans, or images like rashes or fractures are difficult to interpret without expert help.
  • There is no unified platform that combines medical insight + lifestyle guidance in a personalized, easy way.

As a result, many individuals end up:

  • Making unhealthy food decisions
  • Misinterpreting their symptoms
  • Or completely ignoring health advice because it feels overwhelming.

Solution : MedHack: Your AI Health Companion

MedHack provides instant, personalized, and actionable health guidance in one place.

1) MedScan — AI-Based Medical Understanding

  1. Upload X-rays, reports, or skin images
  2. AI analyzes the condition and explains it in simple words
  3. Provides possible causes and recommendations
  4. Encourages informed decisions — not blind self-diagnosis

2) Diet Planner Agent — Personalized Meal Planning

  • Enter your age, weight, lifestyle habits, budget, and goals
  • The agent asks follow-up questions to understand your real daily routine
  • Generates a custom 7-day diet plan:
    1. Nutritionally balanced
    2. Based on personal restrictions (vegan, allergies, etc.)
    3. Tailored for weight loss, gain, or general fitness
  • Plan can be downloaded as PDF or sent via email instantly

Secure by Design (Auth0 Integration)

This ensures the app can scale responsibly and safely.

  • User authentication protects personal health data
  • Role-based access lets free users try basic features
  • Premium role unlocks advanced scanning and detailed diet planning
  • Auth0 Actions automate role assignment and secure feature access This makes MedHack practical, trustworthy, and ready for real-world use ## How I Used Auth0 for AI Agents to Secure MedHack <!-- Explain how you leveraged Auth0 for AI Agents to secure your application and enable agent authentication. --> MedHack handles personal medical data, so security and controlled access were critical. I integrated Auth0 for AI Agents to handle authentication, authorization, and tool access permissions.

1) User Authentication

Users sign in using Auth0’s hosted login page.
In middleware.ts, I protect private routes:

// middleware.ts
import { auth0 } from "@auth0/nextjs-auth0";

export default auth0.withMiddlewareAuthRequired();
Enter fullscreen mode Exit fullscreen mode

This ensures only authenticated users can access the dashboard, Diet Planner, or MedScan features.

2) Role-Based Access Control (RBAC)
Role: Access
free_user : Basic MedScan + simple diet suggestions
pro_user : Full diet generator, detailed scan reasoning, PDF + email export

Roles are assigned in Auth0 Dashboard (or via Actions when a user upgrades).

Roles defined in code (auth0-fga.ts)

export const roles = {
  FREE_USER: {
    name: 'free_user',
    permissions: [
      "use:vision_agent",
      "read:health_data"
    ]
  },
  PRO_USER: {
    name: 'pro_user',
    permissions: [
      "use:vision_agent",
      "use:diet_agent",
      "read:health_data",
      "write:health_data",
      "export:pdf",
      "send:email"
    ]
  }
};
Enter fullscreen mode Exit fullscreen mode

3) Injecting Permissions into JWT (Auth0 Action)

I added an Auth0 Post-Login Action so user tokens contain permissions:

exports.onExecutePostLogin = async (event, api) => {
  const namespace = "https://medhack.ai";
  const role = event.authorization?.roles?.[0] ?? "free_user";

  const permissions = role === "pro_user"
    ? roles.PRO_USER.permissions
    : roles.FREE_USER.permissions;

  api.idToken.setCustomClaim(`${namespace}/permissions`, permissions);
  api.accessToken.setCustomClaim(`${namespace}/permissions`, permissions);
};

Enter fullscreen mode Exit fullscreen mode

4) Server-Side Permission Enforcement

Before running any agent or API call, I verify permission.

// lib/authorization.ts
import { auth0 } from "@auth0/nextjs-auth0";

export async function withAuthorization(requiredPermission: string) {
  const session = await auth0.getSession();
  const userPermissions = session?.user?.["https://medhack.ai/permissions"] ?? [];

  if (!userPermissions.includes(requiredPermission)) {
    throw new Error(`Forbidden: Missing Permission → ${requiredPermission}`);
  }
}

Enter fullscreen mode Exit fullscreen mode

Example Use (Protect Diet Agent API) :

// app/api/agents/diet/route.ts
import { withAuthorization } from "@/lib/authorization";

export async function POST(request: Request) {
  await withAuthorization("use:diet_agent");

  // ...run AI agent logic
}
Enter fullscreen mode Exit fullscreen mode

✅ Free users cannot call the diet agent.
✅ Pro users can.
5) Token Vault: Secure Tool Access

When agents call external APIs (OCR, vision, food nutrition search, email sender), I use the Auth0 Token Vault, so:

  • Tokens never reach frontend
  • AI agents get temporary scoped access
import { getAccessToken } from "@auth0/nextjs-auth0";

const { accessToken } = await getAccessToken({
  scopes: ["send:email", "export:pdf"]
});

Enter fullscreen mode Exit fullscreen mode

6) FGA-Style Ownership Rule (User Data Privacy)

Each user has access only to their own generated plans & scans:

export function canAccessResource(resourceOwnerId: string, currentUserId: string) {
  return resourceOwnerId === currentUserId;
}
Enter fullscreen mode Exit fullscreen mode

✅ No one can view or download someone else’s medical plan or scan.
This is functionally similar to Auth0 Fine-Grained Authorization (FGA) patterns.
MedHack is secure, scalable, and safe to deploy publicly.

Lessons Learned and Takeaways

...existing content...


💭 Development Retrospective

7 Major Challenges & Solutions

1. AI Model Availability Issues

Problem: Qwen2.5-VL-72B failed in production (404: model not found on free tier)
Solution: Implemented automatic fallback system with 3 models (Gemini → Claude → Llama)
Learning: Always research model availability before deploying; test locally first

2. Auth0 Custom Claims Complexity

Problem: Missed namespace requirement for JWT custom claims (claims weren't appearing in token)
Solution: Added namespace to Auth0 Action: api.idToken.setCustomClaim(${namespace}/permissions, ...)
Learning: Authentication should be designed first, not retrofitted later

3. Client-Side Permission Checks (Security Issue)

Problem: Initially checked permissions in localStorage (could be faked by users)
Solution: Moved all permission checks to backend, verified via JWT custom claims
Learning: Never trust client-side security; backend MUST validate every request

4. Token Management & User Isolation

Problem: API keys shared across users (couldn't track usage or revoke access)
Solution: Created TokenVault class to isolate keys per user, verify ownership before access
Learning: Think about data ownership from day 1; every resource needs an owner

5. Next.js 15 await cookies() Change

Problem: cookies().get() worked in v14 but failed in v15 (must be awaited)
Solution: Updated all cookie access: (await cookies()).get('demo_role')
Learning: Modern frameworks evolve quickly; read release notes carefully

6. Fallback Strategies & Error Handling

Problem: Single model failure = 500 error; no graceful degradation
Solution: Try-catch loop through 3 models; meaningful error messages; detailed logging
Learning: Resilience beats simplicity in production; always have fallbacks

7. Environment Variables Not Loading in Vercel

Problem: Med Scan worked locally but failed in production (undefined API keys)
Solution: Created /api/debug/env endpoint to diagnose issues; added all vars BEFORE deployment
Learning: Create diagnostic endpoints early; you can't debug production without visibility


Key Learnings

About AI Agents:

  • Models are different → test multiple early
  • Prompt engineering matters significantly
  • Fallback systems are critical
  • Context improves results dramatically

About Authentication:

  • Auth0 is powerful but requires understanding OAuth2 basics
  • JWT tokens are self-contained proofs (cryptographically signed)
  • HTTPOnly cookies protect against JavaScript theft
  • Fine-grained authorization requires careful planning

About Full-Stack Development:

  • Backend must NEVER trust client
  • Type safety (TypeScript) prevents runtime errors
  • Logging is your window into production
  • Comprehensive error handling improves UX

Top 10 Insights

  1. Security is not optional → build it in from day 1
  2. Backend never trusts client → verify everything server-side
  3. AI fallbacks are critical → never rely on single model
  4. JWT tokens are elegant → self-contained, cryptographically signed
  5. Type safety catches bugs → use TypeScript for larger projects
  6. Logging saves hours → simple logs enable production debugging
  7. Resilience beats simplicity → handle failures gracefully
  8. Auth should be first → don't retrofit security later
  9. Diagnostic endpoints save time → create /api/debug/* routes
  10. Test full flow, not just functions → integration testing matters

What Went Well

✅ Auth0 integration was simpler than expected
✅ Fine-grained authorization scales beautifully
✅ Comprehensive error handling improved UX
✅ Clean code organization enables fast development
✅ AI fallbacks eliminated downtime
✅ Secure token vault prevents key exposure


What I'd Do Differently

  1. Start Auth0 setup first (it's foundational)
  2. Create architecture diagram early
  3. Test error cases from day 1 (not just happy path)
  4. Set up monitoring before production
  5. Plan database schema early

Development Stats

  • Time: ~60+ hours
  • Challenges: 7 major ones resolved
  • Models tried: 3 approaches
  • Permissions: 10 defined across 3 roles
  • Security layers: 7 (auth, authz, token vault, audit trail, etc.)
  • Lines of code: ~3,000+
  • Production issues: 1 (env vars) - fixed in 30 mins with debug endpoint

Advice for Similar Projects

Building AI Applications:

  • Test multiple models early
  • Implement fallback strategies from day 1
  • Have API cost budget
  • Log which model succeeds

Implementing Auth:

  • Choose Auth0 or similar (don't build your own)
  • Plan permissions before coding
  • Use HTTPOnly cookies
  • Never check permissions client-side only

Full-Stack Development:

  • Start with architecture diagram
  • Plan security first
  • Use TypeScript
  • Log everything
  • Create diagnostic endpoints

Deploying to Vercel:

  • Set env vars BEFORE first deployment
  • Redeploy after adding new vars
  • Update Auth0 callback URLs
  • Test locally thoroughly

Final Thoughts

Great products are built at the intersection of:

  • Clean architecture (organized, maintainable code)
  • Thoughtful security (security-first decisions)
  • Resilient systems (graceful failure handling)

The best learning comes from challenges. Every problem taught me something that makes me a better developer.

If I could give one piece of advice: "Build security and resilience into the foundation. Create diagnostic tools early. Test the complete flow. And remember: you can debug anything if you can see what's happening."


MedHack proves that with proper architecture, thoughtful security, and resilient systems, you can build impressive AI applications quickly.


Top comments (1)

Collapse
 
oguzkhan80 profile image
Oguzhan Bassari

Nice work on MedHack, Agastya! Building tools to improve crucial interactions like doctor-patient communication is really valuable. As someone also developing a platform for a specific professional group (history teachers), I appreciate the focus on enhancing workflows and accessibility.

What was the biggest user experience (UX) challenge you faced when designing an interface that needs to be intuitive for both doctors and patients, who might have very different levels of tech-savviness? Looks like a comprehensive stack you've used! Keep up the great work.