import { auth, currentUser } from "@clerk/nextjs/server"; import { NextRequest } from "next/server"; import log from "./logger"; /** * Get authenticated user ID from request * Handles both session-based auth (web) and Bearer token auth (mobile) * * For mobile apps using Clerk Expo, tokens should be passed as: * Authorization: Bearer */ export async function getAuthUserId(req: NextRequest): Promise { try { // Clerk's auth() should handle both cookies and Bearer tokens automatically // when the request is properly formatted const { userId } = await auth(); if (userId) { log.debug("Authenticated user", { userId }); return userId; } log.debug("No authentication found"); // Log headers for debugging const authHeader = req.headers.get("authorization"); log.debug("Authorization header check", { present: !!authHeader, }); return null; } catch (error) { log.error("Authentication error", error); return null; } } /** * Simplified version that just uses Clerk's built-in auth * This should work with both session cookies and Bearer tokens */ export async function requireAuth(req: NextRequest): Promise { const userId = await getAuthUserId(req); if (!userId) { throw new Error("Unauthorized"); } return userId; }