Integrating Time Doctor with Lovable requires Edge Functions to proxy the Time Doctor API v2. Store your OAuth2 access token in Cloud Secrets, create an Edge Function that reads users, time entries, productivity statistics, and work sessions, and build remote team management dashboards in Lovable's React frontend. Time Doctor combines time tracking with productivity monitoring — screenshots, app/website usage, and distraction alerts — giving managers visibility into how remote teams spend their time.
Why integrate Time Doctor with Lovable?
Time Doctor is used by thousands of remote-first companies to track employee work hours and productivity — particularly for distributed teams where managers cannot observe work directly. Unlike simpler time trackers, Time Doctor captures not just hours but productivity quality: screenshots at configurable intervals, app and website usage categorized as productive or unproductive, distraction alerts when off-task browsing is detected, and work session data showing when employees were active vs idle. This makes Time Doctor data particularly valuable for building management dashboards.
Building a custom Lovable integration with Time Doctor enables management reporting scenarios that go beyond Time Doctor's built-in reports: a combined productivity dashboard that correlates Time Doctor hours with output metrics from other business systems (Jira tickets closed, customer calls made, revenue generated), a team capacity dashboard showing real-time work session status for scheduling decisions, automated daily briefing emails generated from Time Doctor productivity data, and client-facing reports showing verified hours logged against their projects without exposing the full productivity monitoring detail.
Time Doctor's API v2 is hosted at api2.timedoctor.com and uses OAuth2 for authentication. The key concept in Time Doctor's data model is the company scope — all resources (users, time entries, work sessions) are scoped under a company ID, and your API token must have access to that company. The company ID appears in Time Doctor's URL when you're logged in and must be included in most API requests. This tutorial covers OAuth2 token setup, team data access, and building the management dashboard components most commonly requested for Time Doctor integrations.
Integration method
Time Doctor has no native Lovable connector. All Time Doctor API calls use the REST API v2 at api2.timedoctor.com, proxied through Supabase Edge Functions. OAuth2 access tokens are stored in Cloud Secrets and sent as Bearer Authorization headers. Edge Functions fetch users, work sessions, time entries, and productivity statistics — returning management-focused team data to your Lovable frontend.
Prerequisites
- A Lovable project with Cloud enabled
- A Time Doctor account with API access (Business plan or above required for API access)
- A Time Doctor API access token — obtained via OAuth2 at api2.timedoctor.com/oauth/token or from Account Settings → API
- Your Time Doctor company ID — found in the URL when logged into Time Doctor: app.timedoctor.com/company/COMPANY_ID
- Admin-level access to your Time Doctor company to read other users' time and productivity data
Step-by-step guide
Obtain a Time Doctor API access token and store it in Cloud Secrets
Obtain a Time Doctor API access token and store it in Cloud Secrets
Time Doctor API v2 uses OAuth2 for authentication. For server-side integrations like Lovable Edge Functions, you need an access token. The simplest approach for admin access to your own company's data is to use Time Doctor's password-based OAuth2 grant (resource owner credentials), which lets you exchange your username and password for an access token without a browser redirect. To get your access token, you need your Time Doctor company's API credentials. Log into your Time Doctor account, then navigate to app.timedoctor.com/account-settings or the API settings section. You'll find your client ID — for standard API access, Time Doctor uses a public client ID that you can find in their API documentation at timedoctor.com/api. Use this to request a token via their OAuth2 endpoint. For a simpler setup process, Time Doctor also provides access tokens directly in some account settings pages. Check app.timedoctor.com → Account Settings → API Access for a token you can use immediately. Copy the access token and your company ID (visible in the URL when viewing your Time Doctor dashboard). In your Lovable project, open Cloud → Secrets and add: TIMEDOCTOR_ACCESS_TOKEN with your token, and TIMEDOCTOR_COMPANY_ID with your numeric company ID. The company ID is required for most API endpoints — it scopes all requests to your organization's data.
Pro tip: Time Doctor access tokens expire — check the token expiry period in your account settings. If building a production integration, implement token refresh using your refresh token stored as a separate secret (TIMEDOCTOR_REFRESH_TOKEN) and a token-refresh helper in your Edge Function.
Expected result: TIMEDOCTOR_ACCESS_TOKEN and TIMEDOCTOR_COMPANY_ID are stored in Cloud Secrets. Both appear with masked values in the Secrets list.
Create the Time Doctor proxy Edge Function
Create the Time Doctor proxy Edge Function
Time Doctor's API v2 at api2.timedoctor.com requires the company ID as a path component in most endpoints — the pattern is /v1.1/companies/{companyId}/{resource}. This scoping ensures all data access is organization-specific. The Bearer token in the Authorization header authenticates the user making the request, while the company ID in the path scopes to the correct organization. The most valuable Time Doctor data for management dashboards comes from three endpoints: the users list (who is in the team), the work sessions endpoint (who is actively working right now and when they started), and the activity summary endpoint (daily productivity scores, productive vs unproductive time breakdowns). Time entries provide the raw hour logs, while work sessions capture the granular active/idle patterns that distinguish Time Doctor from simpler trackers.
Create a Supabase Edge Function at supabase/functions/timedoctor-proxy/index.ts. Read TIMEDOCTOR_ACCESS_TOKEN and TIMEDOCTOR_COMPANY_ID from Deno.env.get(). Use Authorization Bearer header. Handle CORS. Base URL https://api2.timedoctor.com/api/1.1/companies/{companyId} with the company ID substituted. Accept POST with action and params. Implement: 'list_users' (GET /users with params.status = active), 'get_user' (GET /users/{params.userId}), 'list_work_sessions' with params.userId optional and params.start and params.end date range (GET /work-sessions), 'get_activity_summary' with params.userId and date range (GET /activity/summary with userId, start, end query params), 'list_time_entries' with optional user and date filters (GET /activity/regular with userId, start, end query params), 'get_productivity' with user and date range (GET /statistics/activity with userId, start, end), 'list_projects' (GET /projects). Return all responses as JSON.
Paste this in Lovable chat
1// supabase/functions/timedoctor-proxy/index.ts2import { serve } from "https://deno.land/std@0.168.0/http/server.ts";34const corsHeaders = {5 "Access-Control-Allow-Origin": "*",6 "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",7};89serve(async (req) => {10 if (req.method === "OPTIONS") {11 return new Response("ok", { headers: corsHeaders });12 }13 const token = Deno.env.get("TIMEDOCTOR_ACCESS_TOKEN");14 const companyId = Deno.env.get("TIMEDOCTOR_COMPANY_ID");15 if (!token || !companyId) {16 return new Response(JSON.stringify({ error: "Time Doctor credentials not configured" }), {17 status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },18 });19 }20 const base = `https://api2.timedoctor.com/api/1.1/companies/${companyId}`;21 const authHeaders = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };22 const { action, params = {} } = await req.json();23 let resp;2425 switch (action) {26 case "list_users": {27 const q = new URLSearchParams({ status: params.status || "active" });28 resp = await fetch(`${base}/users?${q}`, { headers: authHeaders });29 break;30 }31 case "get_user":32 resp = await fetch(`${base}/users/${params.userId}`, { headers: authHeaders });33 break;34 case "list_work_sessions": {35 const q = new URLSearchParams();36 if (params.userId) q.set("userId", params.userId);37 if (params.start) q.set("start", params.start);38 if (params.end) q.set("end", params.end);39 resp = await fetch(`${base}/work-sessions?${q}`, { headers: authHeaders });40 break;41 }42 case "get_activity_summary": {43 const q = new URLSearchParams();44 if (params.userId) q.set("userId", params.userId);45 if (params.start) q.set("start", params.start);46 if (params.end) q.set("end", params.end);47 resp = await fetch(`${base}/activity/summary?${q}`, { headers: authHeaders });48 break;49 }50 case "list_time_entries": {51 const q = new URLSearchParams();52 if (params.userId) q.set("userId", params.userId);53 if (params.start) q.set("start", params.start);54 if (params.end) q.set("end", params.end);55 resp = await fetch(`${base}/activity/regular?${q}`, { headers: authHeaders });56 break;57 }58 case "get_productivity": {59 const q = new URLSearchParams();60 if (params.userId) q.set("userId", params.userId);61 if (params.start) q.set("start", params.start);62 if (params.end) q.set("end", params.end);63 resp = await fetch(`${base}/statistics/activity?${q}`, { headers: authHeaders });64 break;65 }66 case "list_projects":67 resp = await fetch(`${base}/projects`, { headers: authHeaders });68 break;69 default:70 return new Response(JSON.stringify({ error: `Unknown action: ${action}` }), {71 status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" },72 });73 }7475 const data = await resp.json();76 return new Response(JSON.stringify(data), {77 status: resp.status, headers: { ...corsHeaders, "Content-Type": "application/json" },78 });79});Pro tip: Time Doctor uses ISO datetime strings for date range parameters. Use format YYYY-MM-DD for date-only values or YYYY-MM-DDTHH:mm:ss for timestamps. For 'today' ranges, use the start of day (T00:00:00) and end of day (T23:59:59) in the user's local timezone.
Expected result: The Edge Function deploys. Calling action 'list_users' returns your team members. Calling 'list_work_sessions' with today's date range returns active session data.
Build a remote team monitoring dashboard
Build a remote team monitoring dashboard
With the Edge Function deployed, you can build a comprehensive team monitoring dashboard. The most useful first view is a team status page showing who is currently working — Time Doctor's work sessions endpoint provides real-time status including whether a session is active or paused. Combining this with today's productivity score from the activity summary gives managers an immediate picture of team engagement. For privacy-conscious implementations, consider which Time Doctor data to surface in your Lovable app. Aggregate productivity scores and work hours are generally appropriate to share with team members themselves, while detailed app/website usage and screenshot data should typically remain admin-only. Design your Lovable UI with role-based visibility — show employees their own data, show managers the team view. For complex RBAC requirements, RapidDev's team can help design the permission layer.
Create a TimeDoctorTeamDashboard component. On mount, call action 'list_users' for all active team members, then for each user call action 'get_activity_summary' with today's date range. Render a responsive grid of team member cards. Each card shows: user name, avatar initials, current status indicator (active session = green dot, no session = grey dot), hours worked today, productivity percentage shown as a colored donut chart (green 80%+, amber 60-79%, red <60%). Add a summary bar at the top: total team members, currently active count, team average productivity score today, and total team hours today. Refresh every 5 minutes automatically.
Paste this in Lovable chat
Pro tip: Time Doctor's activity summary returns 'worked' time (total hours), 'productive' time (time on categorized productive apps/sites), and 'unproductive' time. The productivity percentage = (productive / worked) * 100. Make sure to handle division by zero when worked = 0 (employee hasn't started yet).
Expected result: The dashboard renders team member cards with working status and productivity scores. The active-session dot updates on refresh. The summary bar shows accurate team-wide metrics.
Add weekly productivity reporting and export
Add weekly productivity reporting and export
A daily dashboard is useful for real-time monitoring, but weekly summary reports are what managers use for performance reviews, payroll, and client billing. Adding a weekly view to your Time Doctor Lovable integration requires fetching activity summary data across a 7-day range and aggregating daily figures into weekly totals per user. The Time Doctor API returns daily breakdowns in the activity summary response — each day in the range is a separate entry in the results array. Your frontend aggregates these into weekly totals, calculates averages, and identifies trends (e.g., is productivity improving or declining week over week?). The export feature is particularly valuable for payroll processing — a CSV with employee name, hours logged, and productivity score is typically all that's needed for weekly payroll review.
Add a 'Weekly Report' tab to the TimeDoctorTeamDashboard. Include a week selector defaulting to last week (Monday-Sunday). On tab activation, fetch activity summaries for all team members for the selected week date range. Display a table: columns for team member name, Mon-Sun hours (one column per day), total hours for the week, and average daily productivity %. Color cells red if under 6 hours on a working day. Show a department group by option if users have tags. Add an 'Export CSV' button that downloads name, daily hours, weekly total, and productivity score. At the bottom show team stats: most productive day of the week, average hours per day across the team.
Paste this in Lovable chat
Pro tip: When displaying daily hours for a week, Time Doctor returns 0 entries for days with no activity (weekends, holidays, days off). Ensure your date grid renders all 7 days even when some have no data — show '0h' rather than blank cells for clarity.
Expected result: The Weekly Report tab loads with a 7-day breakdown per team member. All days are shown including zeros. The CSV export downloads correctly formatted data. Week navigation updates all data.
Common use cases
Remote team productivity monitoring dashboard
A remote-first company wants a management dashboard showing real-time team productivity status — who is currently working, their productivity score for today, and total hours logged this week. The Edge Function fetches work sessions and daily activity summaries for all employees, and the frontend renders a team status grid with individual productivity indicators, work hours, and color-coded health scores.
Build a team dashboard at /team-status. Fetch all users from my Time Doctor Edge Function for company ID 12345. For each user, fetch today's work summary (total hours, productive percentage, productive vs unproductive time). Display a responsive grid of team member cards: name, avatar, current status (working/offline), hours today, productivity score as a percentage with color coding (green 80%+, yellow 60-80%, red under 60%). Add a filter to show only currently-active members. Show team totals at the top: total hours logged today, team average productivity score.
Copy this prompt to try it in Lovable
Weekly productivity report with department breakdown
An HR manager needs weekly productivity reports broken down by department for remote headcount reviews. The Edge Function fetches time and activity data for the previous week for all users grouped by their department tag, calculates averages, and the frontend renders a department comparison report with individual drill-down capability and export options.
Build a weekly report page at /weekly-report. Add a week selector defaulting to last week. Fetch time entries and productivity stats for all users for the selected week. Group users by their Time Doctor tags/groups (use as department). For each department show: department name, headcount, average hours per day, average productivity score, top 3 most-used apps. Show an expandable row for each department listing individual team members. Add a CSV export button for the full report. Highlight department rows where average productivity is below the 70% threshold.
Copy this prompt to try it in Lovable
Client billing report with verified hours
A services firm tracks client project work in Time Doctor using project tags and wants a client-facing report showing verified tracked hours for the billing period. The Edge Function fetches time entries filtered by the client's project tag, and the frontend generates a clean billing summary showing total hours, daily breakdown, and the team members who worked on the project — giving clients verified hour counts without exposing internal productivity monitoring data.
Create a billing report page at /billing/{clientId}. Store client-to-Time-Doctor-project-tag mappings in Supabase. Fetch time entries for the current billing period filtered by the client's project tag from my Time Doctor Edge Function. Display: total hours for the period, a calendar view showing daily hours logged, team member breakdown (name, hours contributed), week-by-week trend chart. Add a date range selector. Show a 'Verified' badge indicating hours come from Time Doctor's automated tracking. Include an 'Export PDF' button for client delivery.
Copy this prompt to try it in Lovable
Troubleshooting
API returns 401 Unauthorized with 'Token expired' or 'Invalid token'
Cause: Time Doctor OAuth2 access tokens expire (typically after 7 days to 30 days depending on the grant type). An expired token causes all API requests to fail with 401.
Solution: Check your token's expiry by storing the expiry timestamp when you first obtain it. Implement a token refresh flow: store the refresh token as TIMEDOCTOR_REFRESH_TOKEN in Cloud Secrets, and add a token refresh function that calls the OAuth2 token endpoint with grant_type=refresh_token before the access token expires. For immediate fix, manually obtain a new token and update TIMEDOCTOR_ACCESS_TOKEN in Cloud Secrets.
Activity summary returns empty data even though employees have been working
Cause: The date range parameters use timezone-unaware dates — if the employee is in a different timezone than the API request, the date range may not overlap with their actual work hours.
Solution: Use explicit UTC timestamps for date ranges: start=2026-03-30T00:00:00Z and end=2026-03-30T23:59:59Z. Time Doctor's API processes dates in UTC — employees' local times are converted to UTC internally. If employees are in non-UTC timezones, adjust the date range to cover the full UTC equivalent of their local working hours.
1// Get today's range in UTC2const today = new Date();3const start = new Date(today.getFullYear(), today.getMonth(), today.getDate()).toISOString();4const end = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59).toISOString();403 Forbidden when accessing other users' data
Cause: The API token used is for a regular user account, not an admin or manager. Non-admin users can only access their own data — reading other users' time entries requires admin privileges.
Solution: Use an admin-level account's API token for the integration. In Time Doctor, go to the admin account's settings and generate the API token. Admin tokens can access all users' data within the company scope. If you need granular permissions, contact Time Doctor support to understand available permission levels for API tokens.
Company ID is correct but API returns 'Company not found' errors
Cause: The TIMEDOCTOR_COMPANY_ID secret contains the company's display ID or short name instead of the internal numeric company ID used in the API path.
Solution: Find the correct numeric company ID by calling GET https://api2.timedoctor.com/api/1.1/me after authentication — the response includes the companies array with each company's numeric id field. Use that numeric ID, not the company name or URL slug. Update TIMEDOCTOR_COMPANY_ID in Cloud Secrets with the correct numeric value.
Best practices
- Store both the access token and its expiry timestamp in Cloud Secrets, and build token refresh logic into your Edge Function to handle token expiry gracefully without breaking the integration.
- Implement role-based data visibility in your Lovable app — show individual employees their own productivity data, restrict screenshot and detailed app-usage data to admin roles only.
- Use date ranges aligned to business days (Monday-Friday) when generating weekly reports to avoid confusing low-hour weekends pulling down weekly averages.
- Cache team member lists with a 1-hour TTL since employee rosters change infrequently — always refresh activity and time data in real time.
- Never expose raw productivity scores to individual employees without context — add explanatory text clarifying what the score measures and how it's calculated to avoid misinterpretation.
- When building client-facing reports from Time Doctor data, filter to show only time logged to the client's project tag — never expose full team productivity monitoring data to external clients.
- Monitor for Time Doctor API changes — the API v2 is actively developed and endpoint schemas may update. Subscribe to Time Doctor's developer changelog or periodically test your integration against their API documentation.
Alternatives
Clockify provides simple free time tracking without employee monitoring features — better for teams that want time data without screenshots or app-usage surveillance.
Everhour focuses on project budget tracking with deep PM tool integrations rather than employee productivity monitoring, making it a better fit for project-centric billing workflows.
Harvest combines time tracking with invoicing and expense management without productivity monitoring, suited for client-billing workflows that don't require employee activity tracking.
Frequently asked questions
Does Time Doctor have a native connector in Lovable?
No, Time Doctor is not one of Lovable's 17 shared connectors. Integration requires Edge Functions proxying the Time Doctor API v2. OAuth2 access tokens are stored in Cloud Secrets and never exposed to browser code — all requests route through the server-side Edge Function.
Is displaying Time Doctor productivity data to employees ethical and legal?
This depends on your company's monitoring disclosure policies and local labor laws. In most jurisdictions, employees must be informed that their computer activity is being monitored before Time Doctor is deployed. Displaying aggregate productivity scores to employees in a Lovable dashboard is generally fine — but showing individual screenshots or detailed app-usage logs requires careful consideration of your jurisdiction's privacy regulations (GDPR in Europe, various state laws in the US). Consult your legal team before building employee-facing monitoring dashboards.
What plan is required for Time Doctor API access?
Time Doctor API access requires a Business plan or above. The Basic and Standard plans do not include API access. Enterprise plans include additional API endpoints for more granular productivity data. Check your current plan at app.timedoctor.com → Company Settings → Plan to confirm API access is included before building the integration.
Can I track time across multiple Time Doctor companies in one Lovable app?
Yes — Time Doctor's API is scoped per company ID. To support multiple companies, store multiple sets of credentials in Supabase (one per company) and pass the appropriate company ID and token to the Edge Function based on the authenticated user's company association. This is useful for consultancies that manage Time Doctor accounts for multiple clients.
How do I generate reports that compare this week vs last week automatically?
Calculate the date ranges programmatically using JavaScript Date objects: for last week, find the most recent Monday (previous Monday if today is not Monday) and set the range to that Monday through Sunday. For this week, use the current week's Monday through today. Pass these as ISO date strings to the activity summary endpoint. Store report snapshots in Supabase weekly so you can show historical trends without re-fetching from Time Doctor each time.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation