Skip to content

Mechwarrior727/nextjs-capstone

Repository files navigation

npm run dev

Next.js Google Fit Integration

A Next.js application with Google Fit API integration using Privy authentication for secure OAuth token handling.

Features

  • πŸ” Secure OAuth token management with Privy
  • πŸ“Š Google Fit step count data visualization
  • ⚑ Vercel serverless function optimization
  • πŸ”„ Automatic token refresh and caching
  • 🎨 Responsive UI with real-time status updates
  • 🚨 Comprehensive error handling

Tech Stack

  • Frontend: Next.js 15, React 19, TypeScript, Tailwind CSS
  • Authentication: Privy (OAuth + wallet support)
  • Backend: Next.js API Routes with Vercel serverless functions
  • APIs: Google Fit REST API

Getting Started

Prerequisites

  1. Privy Account: Sign up at privy.io and create an app
  2. Google Cloud Console: Enable Google Fit API and configure OAuth credentials
  3. Vercel Account: For deployment

Installation

  1. Clone the repository:
git clone <your-repo-url>
cd nextjs-capstone
  1. Install dependencies:
npm install
  1. Set up environment variables:
cp .env.example .env.local

Edit .env.local with your actual credentials:

NEXT_PUBLIC_PRIVY_APP_ID=your-privy-app-id
PRIVY_APP_SECRET=your-privy-app-secret

Google OAuth Setup

  1. Go to Google Cloud Console
  2. Create/select a project
  3. Enable the Google Fit API
  4. Configure OAuth consent screen
  5. Create OAuth 2.0 credentials
  6. Add your domain to authorized origins

Privy Configuration

  1. Go to your Privy Dashboard
  2. Navigate to Configuration > App settings
  3. Copy your App ID and App Secret
  4. Add them to .env.local

Development

npm run dev

Open http://localhost:3000 in your browser.

Testing the API locally:

  • API routes work during development
  • Test Google Fit integration at http://localhost:3000/api/fit
  • Check browser console for detailed logs
  • Use browser dev tools to inspect network requests

Building for Production

npm run build

Testing & Deployment

Local Testing

βœ… API routes work locally - you can test everything before deploying:

  1. Start development server:
npm run dev
  1. Test the Google Fit API:
  • Login with Google through Privy
  • Check browser console for OAuth token capture
  • Click "Get Step Data" to test the integration
  • API calls go through http://localhost:3000/api/fit
  1. Debug information available:
  • Browser console shows detailed logs
  • Development UI shows debug panels
  • Network tab shows API requests

Vercel Deployment

πŸš€ Option 1: Automatic Deployment (Recommended)

  1. Push to GitHub:
git add .
git commit -m "Complete Google Fit integration"
git push origin main
  1. Connect to Vercel:
  • Go to vercel.com
  • Click "Import Project"
  • Connect your GitHub repository
  • Vercel will automatically detect it's a Next.js app
  1. Add Environment Variables:

    • Go to your Vercel dashboard
    • Navigate to your project β†’ Settings β†’ Environment Variables
    • Add these variables:
      NEXT_PUBLIC_PRIVY_APP_ID=your-privy-app-id
      PRIVY_APP_SECRET=your-privy-app-secret
      
    • Important: The PRIVY_APP_SECRET should be added as a secure environment variable (not visible in build logs)
  2. Deploy:

  • Vercel automatically builds and deploys
  • Your app will be live at your-project.vercel.app

πŸš€ Option 2: Manual Deployment

  1. Install Vercel CLI:
pnpm add -g vercel
  1. Login to Vercel:
vercel login
  1. Deploy:
vercel --prod
  1. Add Environment Variables:
vercel env add NEXT_PUBLIC_PRIVY_APP_ID
vercel env add PRIVY_APP_SECRET
  • Enter your actual Privy credentials when prompted
  • The PRIVY_APP_SECRET will be stored securely as an environment secret

Environment Variables Setup

Required for both local and production:

  1. Get your Privy credentials:

    • Go to Privy Dashboard
    • Sign in to your account
    • Navigate to your app β†’ Configuration β†’ App settings
    • Copy your App ID and App Secret
  2. Local development (.env.local):

NEXT_PUBLIC_PRIVY_APP_ID=your-app-id-here
PRIVY_APP_SECRET=your-app-secret-here
  1. Vercel production:
    • Option A (Recommended): Add variables in Vercel dashboard:
      • Go to your project β†’ Settings β†’ Environment Variables
      • Add NEXT_PUBLIC_PRIVY_APP_ID and PRIVY_APP_SECRET
      • Mark PRIVY_APP_SECRET as secure (hidden in logs)
    • Option B: Use Vercel CLI:
      vercel env add NEXT_PUBLIC_PRIVY_APP_ID
      vercel env add PRIVY_APP_SECRET

⚠️ Security Note: Never commit .env.local to version control. Add it to .gitignore.

Vercel Configuration

The vercel.json file is configured for optimal Next.js deployment with pnpm:

{
  "buildCommand": "pnpm build",
  "devCommand": "pnpm dev",
  "installCommand": "pnpm install --frozen-lockfile",
  "framework": "nextjs"
}

Note: The project uses pnpm as the package manager. Vercel automatically detects and uses pnpm for installations.

Post-Deployment Steps

  1. Test the live app:

    • Visit your deployed URL
    • Login with Google
    • Test Google Fit integration
  2. Monitor logs:

    • Vercel dashboard β†’ Functions β†’ Logs
    • Check for any API errors
  3. Update DNS (if needed):

    • Point your domain to Vercel's nameservers
    • Configure custom domain in Vercel dashboard

Troubleshooting Deployment

Common issues:

  • Build failures: Check environment variables are set
  • API errors: Verify Privy credentials are correct
  • OAuth issues: Ensure Google OAuth is configured properly
  • Secret not found: Make sure environment variables are added in Vercel dashboard

Check logs:

  • Vercel dashboard β†’ Deployments β†’ View Logs
  • Vercel dashboard β†’ Functions β†’ Logs (for API route errors)
  • Browser console for frontend errors
  • Network tab for API request details

Environment Variable Issues:

  • Ensure PRIVY_APP_SECRET is marked as "secure" in Vercel
  • Check that variable names match exactly (case-sensitive)
  • Verify the values are correct (copy-paste from Privy dashboard)

Runtime Configuration Issues:

  • Remove custom runtime specifications from vercel.json
  • Next.js API routes are handled automatically by Vercel
  • Only specify framework: "nextjs" in vercel.json

Package Manager Issues:

  • Ensure all commands in vercel.json use pnpm instead of npm
  • The installCommand should be pnpm install --frozen-lockfile
  • Vercel should automatically detect and use pnpm

How It Works

Authentication Flow

  1. User logs in with Google via Privy
  2. Privy captures OAuth tokens (stored securely server-side)
  3. Frontend attempts direct Google Fit API call using captured tokens
  4. Fallback to server-side API route if direct call fails
  5. Step data is processed and returned with visualization

Current Implementation Notes

Frontend-Only Approach:

  • Uses useOAuthTokens hook to capture Google OAuth tokens
  • Makes direct Google Fit API calls from the browser
  • Falls back to server-side API route if needed
  • Includes comprehensive debugging and error handling

OAuth Token Access:

  • The useOAuthTokens hook should capture tokens during OAuth flow
  • If tokens aren't captured, try clicking "Refresh Google Auth"
  • Direct API calls may face CORS restrictions in some browsers

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Frontend      │───▢│  Direct API Call │───▢│  Google Fit API β”‚
β”‚   (Next.js)     β”‚    β”‚  (Browser)       β”‚    β”‚                 β”‚
β”‚                 β”‚    β”‚                  β”‚    β”‚                 β”‚
β”‚ β€’ useOAuthTokensβ”‚    β”‚ β€’ OAuth Token    β”‚    β”‚ β€’ Step Data     β”‚
β”‚ β€’ Error Handlingβ”‚    β”‚ β€’ Fallback Route β”‚    β”‚ β€’ Processing    β”‚
β”‚ β€’ UI Feedback   β”‚    β”‚ β€’ Comprehensive  β”‚    β”‚ β€’ Visualization β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Security Features

  • OAuth token capture: Uses Privy's secure useOAuthTokens hook
  • Direct API calls: Minimal server involvement for testing
  • Fallback mechanism: Server-side API route as backup
  • Token refresh: Automatic reauthorization on expiration
  • Error boundaries: Graceful failure handling
  • Input validation: Prevents injection attacks

API Reference

/api/fit - Get Google Fit Step Data

Method: POST

Request Body:

{
  "privyAccessToken": "string",
  "userId": "string"
}

Response:

{
  "success": true,
  "data": {
    "days": [
      {
        "date": "2024-01-01",
        "steps": 8500
      }
    ],
    "total": 42500
  },
  "metadata": {
    "daysCount": 5,
    "dateRange": {
      "start": "2024-01-01T00:00:00.000Z",
      "end": "2024-01-05T23:59:59.999Z"
    },
    "cached": false
  }
}

Error Responses:

{
  "error": "Error description",
  "code": "ERROR_CODE",
  "action": "suggested_action"
}

Troubleshooting

Common Issues

  1. "No Google OAuth token found"

    • Ensure user logged in with Google
    • Check OAuth scopes include fitness data
    • Verify Privy app secret is correct
  2. "Token expired"

    • The system automatically attempts reauthorization
    • If persistent, check Google OAuth settings
  3. Build failures

    • Ensure all environment variables are set
    • Check Vercel function logs for detailed errors

Debug Information

The app includes debug panels (development mode only) that show:

  • Authentication status
  • Token availability
  • API response details
  • Error information

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

Quick Start Summary

  1. Setup: Add PRIVY_APP_SECRET to .env.local
  2. Test Locally: npm run dev β†’ Login with Google β†’ Check console logs
  3. Deploy: Push to GitHub β†’ Connect to Vercel β†’ Add environment variables
  4. Verify: Test live app with Google Fit integration

License

This project is licensed under the MIT License.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors