Learn how to integrate Lovable with Fitbit API in just a few simple steps. Sync your data effortlessly for a seamless, connected wearable experience.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
For the integration to work, you must first register your app on Fitbit’s developer portal to get a Client ID and Client Secret. Then, open your Lovable project and add the following constants at the top of your new file. Replace the placeholder values with your actual credentials.
// src/fitbitIntegration.ts
// Replace these values with your actual Fitbit credentials from the developer portal.
const CLIENTID = 'YOURFITBITCLIENTID';
const CLIENTSECRET = 'YOURFITBITCLIENTSECRET';
const REDIRECT_URI = 'https://your-lovable-app.com/fitbit/callback'; // make sure this URL is registered in Fitbit
Create a new TypeScript file named fitbitIntegration.ts
in your project's src
folder. Copy and paste the following code into that file. This module provides helper functions to generate the Fitbit authorization URL, exchange the authorization code for an access token, and fetch user data from Fitbit.
// src/fitbitIntegration.ts
// Insert your Fitbit credentials here (as seen in Step One)
const CLIENTID = 'YOURFITBITCLIENTID';
const CLIENTSECRET = 'YOURFITBITCLIENTSECRET';
const REDIRECT_URI = 'https://your-lovable-app.com/fitbit/callback';
/**
- Generates the Fitbit authorization URL to start the OAuth2 flow.
*/
export function getFitbitAuthUrl(): string {
const scope = 'activity sleep heartrate'; // adjust the scope as necessary
const authUrl = https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=${encodeURIComponent(scope)};
return authUrl;
}
/**
- Exchanges the authorization code returned by Fitbit for an access token.
*/
export async function exchangeCodeForToken(code: string): Promise {
const url = 'https://api.fitbit.com/oauth2/token';
// Build the request body using URLSearchParams.
const body = new URLSearchParams();
body.append('clientid', CLIENTID);
body.append('granttype', 'authorizationcode');
body.append('redirecturi', REDIRECTURI);
body.append('code', code);
// Create a Basic Authentication header using Base64 encoded clientid:clientsecret.
const authHeader = 'Basic ' + btoa(${CLIENT_ID}:${CLIENT_SECRET});
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': authHeader
},
body: body.toString()
});
if (!response.ok) {
throw new Error(Token exchange failed: ${response.statusText});
}
return await response.json();
}
/**
- Fetches the Fitbit user profile using the provided access token.
*/
export async function fetchFitbitUserData(accessToken: string): Promise {
const url = 'https://api.fitbit.com/1/user/-/profile.json';
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
if (!response.ok) {
throw new Error(Fetching user data failed: ${response.statusText});
}
return await response.json();
}
In the main file where your project defines routing (for example, app.ts
or index.ts
), add a new route to handle Fitbit’s callback. This route will capture the authorization code sent by Fitbit and exchange it for an access token using the module created in Step Two. Insert the following code in your routing file:
import { exchangeCodeForToken } from './fitbitIntegration';
// Define a function to handle the Fitbit callback.
async function handleFitbitCallback(request: Request): Promise {
// Extract the query parameter 'code' from the request URL.
const urlParams = new URL(request.url).searchParams;
const code = urlParams.get('code');
if (!code) {
return new Response("Missing 'code' parameter.", { status: 400 });
}
try {
const tokenData = await exchangeCodeForToken(code);
// Here you can store the tokenData for future API calls (e.g., in a session or database).
return new Response("Fitbit integration successful.", { status: 200 });
} catch (error) {
return new Response("Error during Fitbit integration: " + error, { status: 500 });
}
}
// Register the route for Fitbit callback.
// For example, if your Lovable project uses a simple routing mechanism, add:
// router.get('/fitbit/callback', handleFitbitCallback);
// If the project setup is different, integrate the above function where you handle route definitions.
In your Lovable project’s user interface file (for instance, a dashboard or settings component), you need to provide a way for users to initiate the Fitbit OAuth flow. Import the getFitbitAuthUrl
function from your integration module and use it to set the href
attribute in a link or trigger window navigation when the button is pressed. Insert the following code snippet at the appropriate section in your UI file:
import { getFitbitAuthUrl } from './fitbitIntegration';
const fitbitAuthUrl = getFitbitAuthUrl();
// Example: Using an HTML tag as the “Connect with Fitbit” button.
// Add the following HTML in your component/template where you want the button to appear:
/*
Connect with Fitbit
*/
To complete the integration, ensure that:
// In your Lovable project settings, make sure the routes and modules are properly imported and registered.
// Test the integration by clicking on "Connect with Fitbit" from your UI. This should redirect you to Fitbit's login page.
// Once authorized, Fitbit will redirect back to your callback URL (i.e., /fitbit/callback) and complete the token exchange.
Review all inserted code snippets and ensure that URLs, credentials, and scopes match your application settings. Following these detailed steps will integrate your Lovable project with the Fitbit API without requiring any terminal commands for dependency installation.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.