This is a submission for the Auth0 for AI Agents Challenge
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.
Live Demo: https://med-hack.vercel.app/
Github Repo : https://github.com/kris70lesgo/Medhack
Watch the video for the live demonstration of medhack
{% youtube q7nSmOY2_j4 %}
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

Healthcare guidance today is fragmented and inefficient:
As a result, many individuals end up:
MedHack provides instant, personalized, and actionable health guidance in one place.
This ensures the app can scale responsibly and safely.
<!-- 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();
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"
]
}
};
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);
};
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}`);
}
}
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
}
✅ 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:
import { getAccessToken } from "@auth0/nextjs-auth0";
const { accessToken } = await getAccessToken({
scopes: ["send:email", "export:pdf"]
});
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;
}
✅ 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.
...existing content...
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
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
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
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
await cookies() ChangeProblem: 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
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
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
/api/debug/* routes✅ 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
Building AI Applications:
Implementing Auth:
Full-Stack Development:
Deploying to Vercel:
Great products are built at the intersection of:
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.
<!-- Thanks for participating! -->